Search code examples
c#asp.netasp.net-mvcasp.net-identityclaims-based-identity

When are the Asp.Net Identity are created and assigned to the user?


I am trying to wrap my head around the Asp.Net Identity. But unfortunately the available documentation is not very clear or I feel it is just over my head :(

However, follow is a high level understanding based on all day research and reading. When a user is logged in, a collection of claims is provided. Using these claims you can enable/disable feature. For example, if a user claims their age is 30 years old, then you can allow them to view adult only content, but if they claim to be 17 then you deny access to him/her :). Additionally, roles to users like "Admin", "Super Users"... can be used to enable/disable access. If the users with "Admin" role, they you can allow them to access a X action method.

However, there are lots of thing that are confusing me and not allowing me to clearly wrap my head around it.

Scenario

Assume I want to create a new an application with one controller. This controller has two action methods Add and Edit. I am guessing that I will need two claims for each users

new Claim {
  UserId = 10, 
  ClaimType = "Can Add", 
  ClaimValue = null
},

new Claim {
  UserId = 10, 
  ClaimType = "Can Edit", 
  ClaimValue = null
}

new Claim {
  UserId = 5, 
  ClaimType = "Can Edit", 
  ClaimValue = null
}

In this case the user with the Id = 10 "Can Add" and "Can Edit" but the user with the UserId = 5 "Can Add" by is can't edit.

When are these claims are created and assigned to the user? Do I create these claims as needed by manually inserting them in the AspNetUserClaims table? Do I assign them to the users from their profile?

What if I need to add a new claim in the future, dI I need to manually assign this new claim to all the users manually? or is there a way to assign these claims to a default role where the users can inherit?

This may not be a great question, but answering it will help me understand the Identity better.


Solution

  • Claims should be set when the user login. You should not set it directly in the database. See this post to understand when to set claims.

    A claim is information about the user. You can then use that information for authorization (or anything else).

    Note that you should always set a value to your Claims or else you might run into inexistant claim error.