【问题标题】:Adding Claim for OWIN ClaimsIdentity.AddClaim() from database. ASP.NET Web API从数据库中为 OWIN ClaimsIdentity.AddClaim() 添加声明。 ASP.NET Web API
【发布时间】:2019-02-17 07:45:27
【问题描述】:

我正在使用 Entity Framework 测试一个 .NET 4.7 Web Api 项目,并考虑为用户添加声明以限制对某些 Web api 的访问

我遇到的每个示例/教程(下面的代码示例)都提供了有关添加新 Identity.AddClaim() 的此类示例。

通过 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;
        }
    }

【问题讨论】:

    标签: asp.net oauth-2.0 asp.net-web-api2 owin claims-based-identity


    【解决方案1】:

    在这里和那里浏览了几个建议后,我发现最好的建议是开始一个新项目,并在 Wep API 2 项目设置向导中检查个人用户帐户设置

    这允许使用 Microsoft 开箱即用的角色和身份服务创建数据库表

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

    【讨论】:

    • 您可以在我的回答中添加一条评论,在其中您承认该建议确实是您正在寻找的。​​span>
    • 很抱歉在回答您自己的问题时没有意识到这会删除您的 cmets。
    猜你喜欢
    • 1970-01-01
    • 2019-05-01
    • 2019-07-21
    • 2017-08-05
    • 2015-04-05
    • 2016-01-01
    • 2018-12-16
    • 2015-02-16
    • 1970-01-01
    相关资源
    最近更新 更多