Asp.net mvc 如何告诉ASP.NET MVC角色管理器使用我的IUserRoleStore实现?
标题说明了这一点。我已经实现了自定义IUserRoleStore,现在当我使用AuthorizeAttribute或User.IsInRole时,如何使框架调用它?承载声明和角色的标识由Asp.net mvc 如何告诉ASP.NET MVC角色管理器使用我的IUserRoleStore实现?,asp.net-mvc,authorization,asp.net-identity,Asp.net Mvc,Authorization,Asp.net Identity,标题说明了这一点。我已经实现了自定义IUserRoleStore,现在当我使用AuthorizeAttribute或User.IsInRole时,如何使框架调用它?承载声明和角色的标识由用户管理器创建,它在创建时传递用户存储。如果您有自己的UserStore实现,您只需实现IUserRoleStore接口,即 public class UserStore : // ... IUserRoleStore<IdentityUser>,
用户管理器创建,它在创建时传递用户存储
。如果您有自己的UserStore
实现,您只需实现IUserRoleStore
接口,即
public class UserStore : // ...
IUserRoleStore<IdentityUser>,
// ...
然后,在创建UserManager
时,将派生的UserStore
传递给它
更新
此代码创建一个标识
var identity = await _userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
identity.AddClaim(new Claim("someclaim", "somevalue"));
Request.GetOwinContext().Authentication.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);
它存储在加密的cookie(或令牌)中,由OWIN中间件通过IPrincipal
提供。这就是为什么您可以在不点击数据库的情况下读回用户属性,例如
private string GetClaim(string claimType)
{
var principal = (ClaimsPrincipal)Thread.CurrentPrincipal;
return principal.Claims.Where(c => c.Type == claimType).Select(c => c.Value).FirstOrDefault();
}
或者通过User.IsInRole()
/User.Identity.GetUserId()
它适用于我,我将authorized属性
用于角色,例如
[RoutePrefix("account"), Authorize(Roles = "Admin")]
public class AccountController : ApiController
// ...
当用户登录时,UserStore
上的GetRolesAsync
被调用,在随后的访问中,角色从cookie中可用。我在用这个。MySQL需要确保您的UserStore
实现了IUserRoleStore
接口,否则它将无法获取角色。AuthorizeAttribute/User.IsInRole会在您的用户IPrincipal的ClaimsEntity中查找任何RoleClaimTypes。UserManager的ClaimSideEntityFactory通常在生成成为登录cookie的ClaimSideEntityFactory时通过IUserRoleStore生成这些声明。但在检查角色成员身份时,不会直接调用自定义IUserRoleStore方法。请确保在自定义UserManager中使用新的ASP.NET Identity framework时,web.config不会启用旧的角色管理器。确保将其设置为false
<system.web>
<roleManager enabled="false" />
</system.web>
这在我们的一个项目中被设置为true,每当我们尝试使用时,都会出现奇怪的sql异常,几乎让我们发疯。使用Microsoft提供的Entity Framework UserStore或您自己的自定义UserStore时,IsInRole或[Authorize]?检查更新的答案。我知道。但是这个UserStore在AccountController的范围内,它怎么可能与另一个controller上设置的AuthorizeAttribute相关呢。我的实现还有来自IUserStore接口的方法,它们在应该调用的时候被调用。来自IUserRoleStore的方法从未被调用。
<system.web>
<roleManager enabled="false" />
</system.web>