从数据库中为 OWIN ClaimsIdentity.AddClaim() 添加声明。 ASP.NET 网页 API
Adding Claim for OWIN ClaimsIdentity.AddClaim() from database. ASP.NET Web API
我正在使用 Entity Framework 测试 .NET 4.7 Web Api 项目并考虑为用户添加声明以限制对某些 Web api 的
的访问
我遇到的每个 example/tutorial(下面的代码示例)都给出了此类添加新 Identity.AddClaim() 的示例。
通过 if 条件为不同角色的多个用户添加新声明当然不是这样,所以我希望使用数据库 table 来获取 context.UserName 的角色数据并且然后用该数据提出新的声明,例如
Identity.AddClaim(new Claim(ClaimTypes.Role, [database.user.role]));
不过,我还没有找到对这种方法的建议。
这是推荐的方法吗?如果是,是否有针对用户角色应遵守的特定 table 架构?
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;
}
}
在仔细阅读了一些建议之后,我发现最好的建议是开始一个新项目,并在 Wep 中检查个人用户帐户设置 API 2 项目设置向导
这允许使用 Microsoft 开箱即用角色和身份服务内联创建数据库表
然后您可以使用 RoleManager 分配角色并使用 userManager 获取用户角色,您可以使用 userManager 在 GrantResourceOwnerCredentials 方法中创建声明
我正在使用 Entity Framework 测试 .NET 4.7 Web Api 项目并考虑为用户添加声明以限制对某些 Web api 的
的访问我遇到的每个 example/tutorial(下面的代码示例)都给出了此类添加新 Identity.AddClaim() 的示例。
通过 if 条件为不同角色的多个用户添加新声明当然不是这样,所以我希望使用数据库 table 来获取 context.UserName 的角色数据并且然后用该数据提出新的声明,例如
Identity.AddClaim(new Claim(ClaimTypes.Role, [database.user.role]));
不过,我还没有找到对这种方法的建议。
这是推荐的方法吗?如果是,是否有针对用户角色应遵守的特定 table 架构?
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;
}
}
在仔细阅读了一些建议之后,我发现最好的建议是开始一个新项目,并在 Wep 中检查个人用户帐户设置 API 2 项目设置向导
这允许使用 Microsoft 开箱即用角色和身份服务内联创建数据库表
然后您可以使用 RoleManager 分配角色并使用 userManager 获取用户角色,您可以使用 userManager 在 GrantResourceOwnerCredentials 方法中创建声明