ASP.NET Identity - Confusion about [Authorize] And RoleManager

ぐ巨炮叔叔 提交于 2019-12-06 02:16:15

The Authorize attribute doesn't know anything about ASP.NET Identity, or any other identity system. It simply works with IPrincipal and IIdentity interfaces that the MVC framework sets up for you.

ASP.NET Identity uses a ClaimsIdentity object, which implements IIdentity.

So the Framework, via the UserManager creates an authentication ticket. When a page loads, it loads this authentication ticket, decrypts it, and creates the necessary principal and identity and role objects.

Then, the Authorize attribute just basically checks User.IsInRole("Blah") when you say

[Authorize(Roles="Blah")]

It's actually a little bit simpler than that. When a user logs in, these lines in the AccountController creates a ClaimsIdentity and the auth middleware sets a cookie...

var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);

The roles information is read from the database when the ClaimsIdentity is created. The identity (including the roles) is serialized and encrypted into the cookie. On subsequent requests, the ClaimsIdentity is decrypted and deserialized from the cookie by the middleware. The identity is attached to the thread, and that's what the AuthorizeAttribute uses to determine if the user is in a role. You can also programmatically access the ClaimsIdentity using User.Identity in a controller.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!