Ale*_*lex 5 c# asp.net authentication asp.net-mvc claims-based-identity
我们在 MVC 5 应用程序中使用 ASP.NET Identity。我们有一个页面,允许管理员添加用户及其声明。但是,使用以下几行,我可以继续添加具有相同角色声明的用户,从而创建重复的项目(该AspNetUserClaims表有一个主键“自动编号”列,因此我们可以继续向同一用户添加相同的角色):
var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
await userManager.AddClaimAsync("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
new Claim(ClaimTypes.Role, "SomeRole"));
Run Code Online (Sandbox Code Playgroud)
请注意,我添加的是任意用户的声明,而不是登录用户的声明。如果是登录用户,我可以简单地调用User.IsInRole("SomeRole"). 是xxxx用户的 GUID。
在这种情况下,我正在考虑在添加角色之前使用以下数据库调用进行检查:
public static async Task<bool> UserHasClaim(string userId,
string claimType, string claimValue)
{
using (var db = new MyEntities())
{
return await db.AspNetUserClaims
.AnyAsync(x => x.UserId == userId && x.ClaimType ==
claimType && x.ClaimValue == claimValue);
}
}
Run Code Online (Sandbox Code Playgroud)
有一个更好的方法吗?我知道它ClaimsPrincipal包含一个方法.HasClaim(...),但我不知道如何ClaimsPrincipal从该用户创建一个方法,然后运行该方法。谢谢。