如何在MVC Core 2.0(使用aspnetcore.identity(中创建自定义授权索赔以验证自定义用户布尔属性?我已经扩展了IdentityUser(ApplicationUser(,以包括一个布尔值" ISDEVEVELER"。我正在使用基于索赔的身份验证,并想添加自定义索赔,但不确定从哪里开始。我如何创建一个自定义主张:
- 找到当前(自定义(核心用户。
- 评估自定义身份用户布尔值?
我了解核心身份声明MSDN:基于索赔的身份验证,但对自定义索赔是新手,因此我不确定从哪里开始。我发现的在线文档不起作用或不符合我的方案。
因此,您需要在某个地方创建自定义索赔,然后通过自定义策略或手动进行检查。
1(添加
的自定义索赔JWTBEARER身份验证
您可以做这样的事情:
在您的控制器操作中,您可以添加 custom claim
:
[HttpGet]
public dynamic GetToken(string login, string password)
{
var handler = new JwtSecurityTokenHandler();
var sec = "12312313212312313213213123123132123123132132132131231313212313232131231231313212313213132123131321313213213131231231213213131311";
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(sec));
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
var user = GetUserFromDb(login);
var identity = new ClaimsIdentity(new GenericIdentity(user.Email), new[] { new Claim("user_id", user.Id) });
if (user.IsDeveloper)
identity.AddClaim(new Claim("IsDeveloper", "true"));
var token = handler.CreateJwtSecurityToken(subject: identity,
signingCredentials: signingCredentials,
audience: "ExampleAudience",
issuer: "ExampleIssuer",
expires: DateTime.UtcNow.AddSeconds(100));
return handler.WriteToken(token);
}
asp.net核心身份身份验证
您需要实现自定义IUserClaimsPrincipalFactory
或将UserClaimsPrincipalFactory
用作基类:
public class ApplicationClaimsIdentityFactory: Microsoft.AspNetCore.Identity.UserClaimsPrincipalFactory <ApplicationUser>
{
UserManager<ApplicationUser> _userManager;
public ApplicationClaimsIdentityFactory(UserManager<ApplicationUser> userManager,
IOptions<IdentityOptions> optionsAccessor):base(userManager, optionsAccessor)
{}
public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
{
var principal = await base.CreateAsync(user);
if (user.IsDeveloper)
{
((ClaimsIdentity)principal.Identity).AddClaims(new[] {
new Claim("IsDeveloper", "true")
});
}
return principal;
}
}
然后您需要在Startup.ConfigureServices
中注册:
services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, ApplicationClaimsIdentityFactory>();
2(检查索赔
自定义策略
在Startup.ConfigureServices
中:
services.AddAuthorization(options =>
{
options.AddPolicy("Developer", policy =>
policy.RequireClaim("IsDeveloper", "true"));
});
保护您的开发人员行动:
[Authorize(Policy = "Developer"), HttpGet]
public string DeveloperSecret()
{
return "Hello Developer"
}
手动检查索赔
控制器中的某个地方:
bool isDeveloper = User.Claims.Any(c => c.Type == "IsDeveloper" && c.Value == "true")
如果您正在使用其他身份验证,则想法应该相同。
在.net 6
中添加自定义值new Claim("AdminStatusIS", AdminStatus.ToString()
然后在程序中使用它。cs
policy.RequireClaim("AdminStatusIs", "True");