Change from Roles authorization to Claims authoriz

2020-04-14 02:08发布

问题:

I have a webforms application which was built with ASP.NET Membership. I migrated to Identities successfully.

I now want to use Claims authorization instead of Roles authorization, but the Role information for the old users has been migrated to the AspNetUserRoles table in the database but the AspNetUserClaims table is empty. New users registered after migration, I can add to AspNetUserClaims with the following code:

IdentityResult result1 = manager.AddClaim(user.Id, new Claim(ClaimTypes.Role, "role"));

But the old users are only registered in the AspNetUserRoles table not in the AspNetUserClaims table.

  1. On login will the claim created include Role information from the AspNetUserRoles table also or only from the AspNetUserClaims table?

  2. Will the User.IsInRole() check both the AspNetUserRoles table and the AspNetUserClaims table?

  3. How can I migrate information from the AspNetUserRoles table to the AspNetUserClaims table?

回答1:

Don't get hooked on "claims" term. Here this is a convenient way to add information into the cookie.

Here actually are 2 types of "claims" - one that is added into the cookie and one that is preserved in AspNetUserClaims table.

When user is logging in, a cookie with identity is created. Identity contains all the claims user has. Claim here is a key-value pair that is added in the cookie as a payload. Cookie claims contains things like User.Id, SecurityStamp, Username some other framework related stuff and... list of roles from AspNetUserRoles. Along with additional claims from AspNetUserClaims.

So what you are trying to add roles into claims - makes no sense. Roles will be in the cookie as claims anyway - added by the framework.

Probably I'm not explaining well - when you debug your application, analyse User property of a controller and look into ClaimsIdentity and see list of all the claims. All my jibbering will make more sense.

To answer your second question - User.IsInRole() does not go into the database. This method only checks information in the cookie, see the source code for yourself: it only checks if cookie contains claims of type ClaimTypes.Role with the name of the role you are trying to check.

Third question... do you still want to do that? You can do a SQL statement, something like insert into aspnetuserclaims (<columns>) select <columns> from aspnetUserRoles inner join aspnetroles on aspnetUserRoles.roleid = aspnetroles.id.

I wrote about what claims go into the cookie in my blog a while ago - you'll get a better understanding how it all comes together.