RSS

Unity Dependency Injection in ASP.NET MVC Authorize Attribute

29 May

Often times, we need custom Authorize attribute used in ASP.NET MVC to customized authorization using our own authorize / authentication service. And with that, we need to inject dependency into the attribute.

In C#, only certain type can be passed into an attribute. To get dependency in an attribute: DependencyResolver.Current.GetService()

public class MyAuthorizationAttribute : AuthorizeAttribute
{
    public IMyAuthService myAuthService { get; set; }

    public PartDAuthorizationAttribute()
    {
        myAuthService = DependencyResolver.Current.GetService<IMyAuthService>();
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            bool auth = myAuthService.IsUserAuthorized();
            if (!auth)
            {
                HandleUnauthorizedRequest(filterContext);
            }
        }
        else
        {
            HandleUnauthorizedRequest(filterContext);
        }
    }
}

Code is written for Unity 3.0 and ASP.NET MVC 4

Advertisements
 
Leave a comment

Posted by on May 29, 2013 in General

 

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

 
%d bloggers like this: