How To Assign Custom Identity To MVC WebApi

In my previous post How to implement Basic aucthentication for MVC WebApi, I left some loose ends. Right after I posted the blog, I got few emals asking how do you go about setting identity of request once user has been authenticated and authorized. When we use Forms authentication for our ASP.Net or MVC application, FormsAuthentication class takes care of setting the cookie and assigning IIdentity object with request. But when we implemented custom authrization, we are responsible for taking care of setting identity as well.

Since I am doing custom authentication and authorization, I have some custom attributes that I need for identity of users of my WebApi. This means I need a custom class that implements IPrincipal or IIdentity. If you are not doing anything fancy, then you can simply use GenericPrincipal or GenericIdentity class. For this discussion I am going to implement my custom class. Following code shows how I implemented it.

public class ServiceIdentity : IPrincipal
  public ServiceIdentity(string userName, string authType)
     Identity = new GenericIdentity(userName, authType);

  public IIdentity Identity
    private set;

  public List<string> Roles { get; set; }

  public bool IsInRole(string role)
     if (null != Roles)
        var query = from r in Roles where string.Compare(role, r, true) == 0 select r;
        return string.IsNullOrWhiteSpace(query.FirstOrDefault());
     return false;

There is more to my implementation than I have shown here for sake of simplicity. So if you see something that looks out of the place, then assume that some parts of the code have been omitted.

Setting Custom Identity in WebApi Request

In previous post I showed how to implement a custom AuthorizeAttribute class. I have added the following code to that class that assign identity to current HttpContext of request.

private void AssignRequestIdentity(string userName, List<string> roles, 
                                   HttpActionContext actionContext)
   var identity = new ServiceIdentity(userName, "Basic");
   identity.Roles = roles;
   if (HttpContext.Current != null)
     HttpContext.Current.User = identity;

Accessing WebApi Identity

Now that identity has been set in the current context of this user, you can access it as shown in code below.

public HttpResponseMessage PostAuctionSettings(AuctionSettingsRequestParameters requestParameters)
   // Get the user name to set in worklfow to identity who initiated this request.
   ServiceIdentity identity = HttpContext.Current.User as ServiceIdentity;
   // .... more code ... removed for discussion .....      

I hope this helps you in providing some insight into how you can set identity of your WebApi.




16.8 °C / 62.2 °F

weather conditions Clear

Monthly Posts

Blog Tags