MVC 5 and using default authentication

I have a question regarding claims in MVC 5.

So, in principle, I have a registered user in the database, now the user will log in, for example:

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 identifier requirement, and then I sign this identity.

Now my questions are:

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

  • And how to use it later in the code?

+7
asp.net-mvc asp.net-mvc-5 owin
source share
1 answer

Installing an identity claim makes your application security more efficient and saves time spent on your database.

The aforementioned method may be known as Claim Conversion, which often involves reading data that translates into claims after successful authentication.

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 additional information for the answer, as described in the comments below.

When using a requirements-based approach, you can also use the claims authorization manager, which can provide centralized / fine-grained control over access to resources and actions.

If you haven’t used the requirements, before you think about actions against resources, rather than role-based permissions. Thus, you can drill right and control access to each resource / action individually, and not have many roles for each of them.

I personally like to use the mixture, but also retain the role as a complaint. That way, I can use standard authorization tags in mvc with roles that read claims and use the thinktecture / ClaimsAuthorization attributes to force the claims authorization manager to accept more complex rules.

A good link to MVC 4 claims-based authentication is available here:

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

+9
source share

All Articles