代码之家  ›  专栏  ›  技术社区  ›  succeed

为OWIN添加索赔索赔实体.AddClaim()来自数据库。ASP.NETWeb API

  •  0
  • succeed  · 技术社区  · 6 年前

    我正在使用EntityFramework测试一个.NET4.7WebAPI项目,并考虑为用户添加声明以限制对某些WebAPI的访问

    通过if条件为不同角色的多个用户添加新声明当然不是这样,因此我希望使用数据库表来获取context.UserName名称然后用这些数据提出一个新的主张。

     Identity.AddClaim(new Claim(ClaimTypes.Role, [database.user.role]));
    

    不过,我还没有找到这种方法的建议。

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            if (context.UserName == "admin" && context.Password == "admin")
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
                identity.AddClaim(new Claim("username", "admin"));
                identity.AddClaim(new Claim(ClaimTypes.Name, "Sourav Mondal"));
                context.Validated(identity);
            }
            else if (context.UserName == "user" && context.Password == "user")
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
                identity.AddClaim(new Claim("username", "user"));
                identity.AddClaim(new Claim(ClaimTypes.Name, "Suresh Sha"));
                context.Validated(identity);
            }
            else
            {
                context.SetError("invalid_grant", "Provided username and password is incorrect");
                return;
            }
        }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   succeed    6 年前

    在这里和那里经过几个建议和我发现的最好的建议是开始一个新的项目与个人用户帐户设置在wepapi2projectsetup向导检查

    这允许使用Microsoft现成角色和标识服务内联创建数据库表

    然后您可以使用RoleManager分配角色,并使用userManager获取用户角色,您可以使用userManager在GrantResourceOwnerCredentials方法中创建声明