Friday, January 18, 2013

MVC4 Authroize Attribute

Most people know about authorize attribute and to customize also, but i had a request where i need to combine below elements 1. The roles will be from an external application 2. I wont know what action or controller they can perform 3. Do not want to code If statement to check the access on each controller 4. Want to make the make the connection of Role and action in the project 5. no usage of sessions So thought of a design 1. Have the role and controller action in web.config
 

    
      
    
        
        
              
    
          
        
              
    
  
2. using cutom configuration as below
 

using System;
using System.Collections;
using System.Text;
using System.Configuration;
using System.Xml;



namespace SomethingCommon
{

    public class RolesSection : ConfigurationSection
    {
        [ConfigurationProperty("", IsDefaultCollection = true)]
        public RoleElementCollection Elements
        {
            get { return (RoleElementCollection)base[""]; }
        }
    }

    public class RoleElementCollection : ConfigurationElementCollection
    {
        const string ELEMENT_NAME = "Role";

        public override ConfigurationElementCollectionType CollectionType
        {
            get { return ConfigurationElementCollectionType.BasicMap; }
        }

        protected override string ElementName
        {
            get { return ELEMENT_NAME; }
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new RoleElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((RoleElement)element).Name;
        }
    }

    public class RoleElement : ConfigurationElement
    {
        const string NAME = "name";

        [ConfigurationProperty(NAME, IsRequired = true)]
        public string Name
        {
            get { return (string)base[NAME]; }
        }

        [ConfigurationProperty("", IsDefaultCollection = true)]
        public ControllerActionElementCollection Elements
        {
            get { return (ControllerActionElementCollection)base[""]; }
        }
    }

    public class ControllerActionElementCollection : ConfigurationElementCollection
    {
        const string ELEMENT_NAME = "ControllerAction";

        public override ConfigurationElementCollectionType CollectionType
        {
            get { return ConfigurationElementCollectionType.BasicMap; }
        }

        protected override string ElementName
        {
            get { return ELEMENT_NAME; }
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new ControllerActionElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((ControllerActionElement)element).Id;
        }
    }

    public class ControllerActionElement : ConfigurationElement
    {
        const string ID = "id";

        [ConfigurationProperty(ID, IsRequired = true)]
        public string Id
        {
            get { return base[ID].ToString(); }
        }
    }


}
2. Have Security attributre in the controller
 
 [Security]
        public JsonResult GetSomething(string sidx, string sord, int page, int rows, string ID)
        {
3. ... Still thinking of cahing but check each controller
 


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;


namespace SomethingBLL
{
    public class SecurityAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
      
             var wccSecurityList = from external system

            var securityList = wccSecurityList as IList ?? wccSecurityList.ToList();
         
            

            //find if the role allows to access the contoller action - if yes then allow , if not then error 
            var controllerAction = filterContext.Controller.ToString() + "-" + filterContext.ActionDescriptor.ActionName;

	
		// to chek
            var isAuthorized = ControllerActionRoles.CheckControllActionForRole(securityList, controllerAction);
                  
            if (!isAuthorized && filterContext.RequestContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectToRouteResult(new
                                                                     RouteValueDictionary(
                                                                     new {controller = "Error", action = "AccessDenied"}));
            }
        }

    }
}

 




4. Code the combines the list and do the magic of checking . please remember the code has some things which i used in my project so it it just an idea ../. RolesSecurity is a model that has 2 string items from web.conifg


 private static List GetRoles()
        {
            var roleSecurityList = new List();
            var section = ConfigurationManager.GetSection("Roles");
            var RolesSection = ConfigurationManager.GetSection("Roles") as RolesSection;

           
            if (RolesSection != null)
            {

                roleSecurityList.AddRange(
                  RolesSection.Elements.Cast()
                                 .SelectMany(Role => Role.Elements.Cast(),
                                             (Role, controllerAction) => new RolesSecurity
                                             {
                                                 RoleName = Role.Name,
                                                 ControllerAction = controllerAction.Id
                                             }));
            }
            else
            {
                throw new Exception("Error");
            }

            return roleSecurityList;
        }


  public static bool CheckControllActionForRole(IList mstRole, string controllerAction)
        {
         
            //get the list from webconfig
            List controllerActionList = GetRoles();        
            var commonList = controllerActionList.Where(x => mstRole.Any(x1 => x1.ToString() == x.RoleName)).Where(x => x.ControllerAction == controllerAction);

            //get only the list for mstRole 
            // check if the controllaction from security is in controlleraction of webconfig
            return commonList.Any();
        }

Unity , Aspect Oriented and Interceptor for C#

Example using MVC 4 , Unity, AOP , Interceptor
 













 
In C#
 
 public class Interceptor : IInterceptionBehavior
    {
        /// 
        /// Returns the interfaces required by the behavior for the objects it intercepts.
        /// 
        /// 
        /// The required interfaces.
        /// 
        public IEnumerable GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }

        /// 
        /// Implement this method to execute your behavior processing.
        /// 
        /// Inputs to the current call to the target.
        /// Delegate to execute to get the next delegate 
        /// in the behavior chain
        /// 
        /// Return value from the target.
        /// 
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            /* Call the method that was intercepted */
            string className = input.MethodBase.DeclaringType.Name;
            string methodName = input.MethodBase.Name;
            string generic = input.MethodBase.DeclaringType.IsGenericType ? string.Format("<{0}>", input.MethodBase.DeclaringType.GetGenericArguments().ToStringList()) : string.Empty;
            string arguments = input.Arguments.ToStringList();
            string preMethodMessage = string.Format("{0}{1}.{2}({3})", className, generic, methodName, arguments);


            var auditLog = new AuditLog();
            auditLog.UserName = Environment.UserName;
            auditLog.ActivityType = string.Format("ClassName - {0} : MethodName - {1}", className, methodName);
            auditLog.Description = preMethodMessage;


            Task.Factory.StartNew(() => Logger.Instance.Log(auditLog));
            
            
            IMethodReturn msg = getNext()(input, getNext);            
            string postMethodMessage = string.Format("{0}{1}.{2}() -> {3}", className, generic, methodName, msg.ReturnValue);
            auditLog.Description = postMethodMessage;
            Task.Factory.StartNew(() => Logger.Instance.Log(auditLog));            
            return msg;
        }

        public bool WillExecute
        {
            get { return true; }
        }
    }

 

Friday, February 09, 2007

Off Topic: Rose Valentine

Off Topic :
Yesterday around dinner time i asked my wife do you like flowers for valentine, she had a look like "who doesn't like flowers", but she said that she doesn't like flowers that much so i can use the money to buy gifts.

After 15 minutes i asked her again that will she feel bad if she doesn't get flowers on valentine when her friends get flowers and her reply was "YES"

Now i am confused i think i will send her flower and get her gift even if she says no. just to be safe and happy.

Investment Bank bonus.. Not that Million

As you all heard news about traders and bankers making millions in bonus. Any idea how much the low end guy makes in Investment banking.
With my knowledge of working for a Investment Banking IT division we make around 8% to 20% of Annual salary. It is not that high but a good money to invest in my 401K.
So when people say they work for Investment Banking don't ask them "are you the trader who got million dollars bonus."

Feel free to add comments with your bonus amount...

Peace

Wednesday, July 19, 2006

Wealth Statistics

Wealth Statistics: How Do You Measure Up Vs. the Average "Wealthy" American? Issue # 452

Good information about how you stack up against the odds

thanks mlebuf - diehards.org

Monday, April 17, 2006

Information : Free Morningstar Reports and X-Ray

Morningstar - A research company that rates the performance of Mutual Funds and Variable Annuities.

Old News: Most people know they can access Morningstar website from library
New news for me : You can access morningstar free from home if you have a library card and live in wake county

Last week after some reallocation of retirement funds i was craving for Morningstar X-Ray, so i went to library to request morningstar access. The person in charge explained to me that i can access Morningstar and other resources from home. You should have a library card and pin (library access code ). I live in wake county, please contact your county library for more information.

Wake county library database

Wake county morningstar

Monday, April 10, 2006

OT: Poem about personal integrity and management

I am trying to learn some management skills to improve my career. The "If" poem caught my attention long time back and still my reference guide for personal management.

"If" poem by Rudyard Kipling same person who wrote jungle book

If you can keep your head when all about you
Are losing theirs and blaming it on you,
If you can trust yourself when all men doubt you
But make allowance for their doubting too,
If you can wait and not be tired by waiting,
Or being lied about, don't deal in lies,
Or being hated, don't give way to hating,
And yet don't look too good, nor talk too wise:
If you can dream--and not make dreams your master,
If you can think--and not make thoughts your aim;
If you can meet with Triumph and Disaster
And treat those two impostors just the same;
If you can bear to hear the truth you've spoken
Twisted by knaves to make a trap for fools,
Or watch the things you gave your life to, broken,
And stoop and build 'em up with worn-out tools:

If you can make one heap of all your winnings
And risk it all on one turn of pitch-and-toss,
And lose, and start again at your beginnings
And never breath a word about your loss;
If you can force your heart and nerve and sinew
To serve your turn long after they are gone,
And so hold on when there is nothing in you
Except the Will which says to them: "Hold on!"

If you can talk with crowds and keep your virtue,
Or walk with kings--nor lose the common touch,

If neither foes nor loving friends can hurt you;
If all men count with you, but none too much,
If you can fill the unforgiving minute
With sixty seconds' worth of distance run,
Yours is the Earth and everything that's in it,
And--which is more--you'll be a Man, my son!


Lines in Bold are my favorite
Disclaimer: If any copyright violation, Please contact me.

Wednesday, April 05, 2006

Question :How to allocate retirement money?

Before my company started to offer Roth 401k, it was easy split of money

401k up to match
Roth IRA
Then max 401k

Now Roth 401k in picture there is no concrete plan how to allocate money. There is no crystal ball to find out what will be the tax situation in the future.

So i am thinking of following the patterns below

Pattern I
401k - up to match
Roth IRA - Max
Roth 401K - Max

or

Pattern II
401k - 50% Max
Roth 401K - 50% Max
Roth IRA - Max

Pattern I Reason
Have most money in taxable account
social security ppl will check only 401k
I can move my roth 401k to roth ira if i leave

Pattern II Reason
Just Hedge on all the side.. you will be average at the end

At the end i decided to go with Pattern I until i can read more about the retirment allocation. As i am reading there are so many factors change equations everytime.

Good conversation about this topic - Die Hards