Custom attribute with WIF claims based authorization

WIF is Microsoft framework for building applications using token security services and claims. Claims are like attributes that describe the user. An example could be the claim Role with a value “Administrator”. Another example, claim Location, value “ManaguaOffice1”.

I can develop an application that can validate claims and act in consequence, like allowing access to some functionality based on Role or location claims.

You can find a nice explanation on the topic here: Introduction to claims based authentication in .Net

I’d like to share an implementation of claims based authorization. This is a solution we developed at a ASP.Net MVC 5 project that uses WIF and OWIN security. We needed to provide a simple way to set authorization for users to access application functionality based on their roles.

As the functionality users have access to is implemented using ASP.Net MVC controllers and controller’s action methods, we needed a custom attribute that could be applied to either controller or action level. We developed an alternative custom attribute, here the code:

//
//Enables custom claims based authorization.
//It uses role claim type.
//Role values get from Auth DB.
//

public class RoleAuthorizeAttribute : AuthorizeAttribute
{

private string[] claimValues;

public RoleAuthorizeAttribute(string allowedRoles)
{
claimValues = allowedRoles.Split(‘,’);

var userProfile = UserProfileRepository.Get(HttpContext.Current.User.Identity);
var identity = UserProfileRepository.AddClaimsRole(userProfile, HttpContext.Current.User.Identity);

}

public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
{

bool isInRole = false;

foreach (var str in claimValues)
{
//It can manages white spaces before and after the role name.

isInRole=HttpContext.Current.User.IsInRole(str.Trim());

if (isInRole) break; //break foreach as user is in one of the required roles.
}

if (isInRole)
{
base.OnAuthorization(filterContext);
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}

}
}

This class inherits from AuthorizaAttribute class and overrides the onAuthorization action filter to allow to “inject” the custom attribute. It can work for more than one role. I’d implement it at the controller like below:

[HttpPost]
[RoleAuthorize("user, admin")]
public ActionResult MyAction(int id)
{
....

 

Cheers.

Leave a Reply

Your email address will not be published. Required fields are marked *