Asp.net-Core

使用擴展的 MVC Core Identity 使用者實現自定義聲明

  • December 13, 2019

如何在 MVC Core 2.0(使用 AspNetCore.identity)中創建自定義授權聲明以驗證自定義使用者布爾屬性?我已經擴展了 IdentityUser (ApplicationUser) 以包含一個布爾值“IsDeveloper”。我正在使用基於聲明的身份驗證,並且想添加自定義聲明,但不確定從哪裡開始。如何創建自定義聲明,該聲明將:

  1. 查找目前(自定義)Core.Identity 使用者。
  2. 評估自定義身份使用者布爾值?

我了解核心身份聲明MSDN: Claims Based Authentication,但對自定義聲明不熟悉,所以我不確定從哪裡開始。我發現的線上文件不起作用或不適合我的方案。

因此,您需要在某處創建自定義聲明,然後通過自定義策略或手動進行檢查。

  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 身份驗證

您需要實現自定義IUserClaimsPrincipalFactoryUserClaimsPrincipalFactory用作基類:

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")

如果您正在使用其他身份驗證,則想法應該是相同的。

引用自:https://stackoverflow.com/questions/48652426