【发布时间】: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