MVC 5 and use of claims default authentication

Alnedru picture Alnedru · Jan 25, 2014 · Viewed 8.1k times · Source

I have a question regarding the claims in MVC 5.

So basically imagine I have a registered user in DB, now the user is going to log in, like so:

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
    // Add more custom claims here if you want. Eg HomeTown can be a claim for the User
    var homeclaim = new Claim(ClaimTypes.Country, user.HomeTown);
    identity.AddClaim(homeclaim);
    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}

So in this case i add a new claim to the identity and then i sign in this identity.

Now my questions are:

  • What is the use of setting this claim? (because i can also get this from the db if i need it, what is the point in this case of claim)

  • And how do i use it later on in the code?

Answer

hutchonoid picture hutchonoid · Jan 25, 2014

Setting the Claim against the identity makes your application security more efficient and saves hitting your database each time.

The method above can be known as a Claims Transformation which often involves reading in data that is transformed into claims after authentication succeeds.

In order to read it later you can do this:

//Get the current claims principal
var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;

//Get the country from the claims
var country = identity.Claims.Where(c => c.Type == ClaimTypes.Country).Select(c => c.Value);

Update

Just to provide some further information to the answer as discussed in the comments below.

With a Claims based approach you also benefit from being able to use a claims authorization manager which can provide a centralized/finely grained access control to resources and actions. 

If you've not used claims before it's best to think of actions against resources rather than role based permissions. That way you can drill right down and control access to each resource/action individually rather than having a multitude of roles for each one. 

I personally like to use a mixture but store the roles as claims too.  That way I can use the standard authorization tags in mvc with roles, which read the claims and use thinktecture's attributes/ClaimsAuthorization to make the claims authorization manager pickup the more complicated rules.

A good link on implementing claims based authentication in MVC 4 is available here:

http://dotnetcodr.com/2013/02/25/claims-based-authentication-in-mvc4-with-net4-5-c-part-1-claims-transformation/