如何告诉ASP.NET MVC角色管理器使用我的IUserRoleStore实现?

问题描述:

标题说明。我已经实现了自定义的IUserRoleStore,现在如何使框架在我使用AuthorizeAttribute或User.IsInRole时调用它?如何告诉ASP.NET MVC角色管理器使用我的IUserRoleStore实现?

+0

使用微软提供的实体框架UserStore或您的自己定制的UserStore? –

+0

我自己的UserStore。 –

+0

检查更新的答案。 –

承载声明的身份&角色由UserManager创建,该创建在创建时获得UserStore。如果你有自己的执行UserStore的,你只需实现IUserRoleStore接口,即

public class UserStore : // ... 
         IUserRoleStore<IdentityUser>, 
         // ... 

如果您使用实体框架UserStore自带的模板,你应该能够覆盖它这样(我没测试过,只是猜测):

public class MyUserStore : UserStore<IdentityUser> 
{ 
    public override Task AddToRoleAsync(IdentityUser user, string role) 
    { 
     // ... 
    } 
} 

然后,当你创建你UserManager,你通过它的派生UserStore

UPDATE

此代码创建它获取存储在加密的cookie(或令牌),并且经由IPrincipal由OWIN中间件提供的身份

var identity = await _userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); 
identity.AddClaim(new Claim("someclaim", "somevalue")); 
Request.GetOwinContext().Authentication.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity); 

。这就是为什么你可以在不碰到数据库的情况下读回用户属性的原因,例如

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()

它适用于我,我使用AuthorizeAttribute与角色,例如,

[RoutePrefix("account"), Authorize(Roles = "Admin")] 
public class AccountController : ApiController 
// ... 

当签约用户,GetRolesAsyncUserStore被调用,在以后的访问角色都可以从cookie。我正在使用这个UserStore。 MySQL是here.确保你的UserStore实现了IUserRoleStore接口,否则它将无法获得角色。

+0

我知道。但是这个UserStore在AccountController的范围内,它如何与另一个控制器上的AuthorizeAttribute设置相关。我的实现也有来自IUserStore接口的方法,当它们应该被调用时会被调用。它的IUserRoleStore方法永远不会被调用。 –

AuthorizeAttribute/User.IsInRole在您的User IPrincipal的ClaimsIdentity中查找任何RoleClaimTypes。 UserManager的ClaimsIdentityFactory通常在通过IUserRoleStore生成ClaimIdentity并生成您的登录Cookie时生成这些声明。但它不会直接调用您的自定义IUserRoleStore方法作为检查角色成员资格的一部分。

确保当您的自定义UserManager使用新的ASP.NET Identity框架时,您的web.config未启用旧的角色管理器。一定要将其设置为false。

 <system.web> 
    <roleManager enabled="false" /> 
    </system.web> 

这被设置为true,我们的项目之一,几乎把我们疯了奇怪的SQL异常,每当我们试图用.IsInRole或[授权]