使用扩展的MVC Core Identity用户实施自定义声明

问题描述 投票:8回答:1

如何在MVC Core 2.0中创建自定义授权声明(使用AspNetCore.identity)以验证自定义用户布尔属性?我扩展了IdentityUser(ApplicationUser)以包括布尔值“ IsDeveloper”。我正在使用基于声明的身份验证,想添加自定义声明,但是不确定从哪里开始。如何创建自定义声明,该声明将:

  1. 查找当前(自定义)Core.Identity用户。
  2. 评估自定义身份用户的布尔值?

我了解核心身份声明MSDN: Claims Based Authentication,但是对于自定义声明来说是新手,所以我不确定从哪里开始。我找到的在线文档不起作用或不适合我的情况。

asp.net-core asp.net-core-mvc asp.net-identity claims-based-identity
1个回答
15
投票

因此,您需要在某处创建自定义声明,然后通过自定义策略或手动进行检查。

1)添加自定义声明

JwtBearer身份验证

您可以执行以下操作:

在返回jwt-token的控制器操作中,您可以添加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 Core身份验证

您需要实现自定义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")

如果您使用其他身份验证,则思路应相同。

© www.soinside.com 2019 - 2024. All rights reserved.