Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC5 Claims version of the Authorize attribute

I'm trying out some of the new stuff in VS2013 RC with MVC5 and the new OWIN authentication middleware.

So, I'm used to using the [Authorize] attribute to limit actions by role but I'm trying to use claims/activity based authorization, and I can't find an equivalent attribute for it.

Is there an obvious one I'm missing or do I need to roll my own? I kinda expected there to be one out of the box.

What I'm looking for specifically is something along the lines of [Authorize("ClaimType","ClaimValue")] I suppose.

Thanks in advance.

like image 432
EightyOne Unite Avatar asked Oct 14 '13 15:10

EightyOne Unite


People also ask

What is the Authorize attribute?

The Authorize attribute enables you to restrict access to resources based on roles. It is a declarative attribute that can be applied to a controller or an action method. If you specify this attribute without any arguments, it only checks if the user is authenticated.

What is Authorize attribute in Web API?

Using the [Authorize] Attribute Web API provides a built-in authorization filter, AuthorizeAttribute. This filter checks whether the user is authenticated. If not, it returns HTTP status code 401 (Unauthorized), without invoking the action.


1 Answers

I ended up just writing a simple attribute to handle it. I couldn't find anything in the framework right out of the box without a bunch of extra config. Listed below.

public class ClaimsAuthorizeAttribute : AuthorizeAttribute {     private string claimType;     private string claimValue;     public ClaimsAuthorizeAttribute(string type, string value)     {         this.claimType = type;         this.claimValue = value;     }     public override void OnAuthorization(AuthorizationContext filterContext)     {         var user = filterContext.HttpContext.User as ClaimsPrincipal;         if (user != null && user.HasClaim(claimType, claimValue))         {             base.OnAuthorization(filterContext);         }         else         {             base.HandleUnauthorizedRequest(filterContext);         }     } } 

Of course, you could remove the type and value params if you were happy to use the controller-action-verb triplet for claims somehow.

like image 171
EightyOne Unite Avatar answered Nov 16 '22 00:11

EightyOne Unite