简体   繁体   English

ASP.NET身份数据库第一个自定义用户和角色

[英]ASP.NET Identity Database First custom user and role

We are trying to implement a Web API project with OWIN and .Net Identity for authentication. 我们正在尝试使用OWIN和.Net Identity实施Web API项目以进行身份​​验证。 We have custom database tables for user and roles, so we need to take database first approach for EF. 我们有针对用户和角色的自定义数据库表,因此我们需要采用数据库优先的方法进行EF。

I have managed to get the Identity to work with our custom account tables (thanks to other stackoverflow threads) but I am stuck on getting roles to work... 我设法使身份可以与我们的自定义帐户表一起使用(由于其他stackoverflow线程),但是我一直坚持让角色起作用...

In summary what I have done so far is implemented a custom IUserStore with the following function 总之,到目前为止,我已经完成了使用以下功能实现的自定义IUserStore

public class IdentityUserStore<TUser> : 
    IUserStore<TUser>, where TUser : IdentityUser
{

    ....

    public Task<TUser> FindByNameAsync(string userName)
    {
        //throw new NotImplementedException();
        IdentityUser user = null;

        Account result = _accountRepo.GetByEmail(userName);

        if (result != null)
        {
            user = new IdentityUser()
            {
                Id = result.Code,
                UserName = result.Email,
                SecurityStamp = result.SecurityStamp,
                PasswordHash = result.PasswordHash,
            };
        }

        return Task.FromResult<TUser>(user as TUser);
    }

    ....
}

** Note the Account entity did not inherit IUser so I had to manually map the minimal data required for IdentityUser. **请注意,帐户实体没有继承IUser,因此我必须手动映射IdentityUser所需的最少数据。

And then override GrantResourceOwnerCredentials function as follows 然后重写GrantResourceOwnerCredentials函数,如下所示

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        UserManager<IdentityUser> _userManager = new UserManager<IdentityUser>(new IdentityUserStore<IdentityUser>());
        IdentityUser user = await _userManager.FindAsync(context.UserName, context.Password);

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));

        context.Validated(identity);

}

With the above the [Authorize] attribute works, but we cant get [Authorize(Roles="XXX")] because the role information is not available. 有了上述内容,[Authorize]属性就可以使用,但是由于角色信息不可用,所以我们无法获得[Authorize(Roles =“ XXX”)]。

Can anyone please help point me to the right direction on retrieving user roles from custom database tables so it works with the .Net Identity framework? 谁能帮我指出从自定义数据库表中检索用户角色的正确方向,以便它与.Net Identity框架一起使用?

Thanks! 谢谢!

The problem with the code above is that you add a role with an unknown (at least for the system) claim type. 上面的代码的问题在于,您添加了一个角色类型(至少对于系统而言)未知的角色。 For roles the predefined claim-type is http://schemas.microsoft.com/ws/2008/06/identity/claims/role or System.Security.Claims.ClaimTypes.Role . 对于角色,预定义的声明类型为http://schemas.microsoft.com/ws/2008/06/identity/claims/roleSystem.Security.Claims.ClaimTypes.Role So please change your code to 因此,请将您的代码更改为

identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim(ClaimTypes.Role, "user"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM