- 參考IdentityServer4實戰 - 基于角色的權限控制及Claim詳解
- 部落客解決了基于TestUser的role claim issue問題,但由于我使用了Aspnet core的Identity,發現按照
的做法沒能實作在WebAPI端的Role驗證功能曉晨Master
[Authorize]
public class IdentityController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
這時是擷取不到role claim的。
3. 跟claim頒發有關的流程可以看我歸納出的圖
4. 話不怎麼會說,直接代碼吧
```
services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySql(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
//添加下面兩行代碼
.AddRoles<IdentityRole>()
.AddClaimsPrincipalFactory<UserClaimsPrincipalFactory<IdentityUser, IdentityRole>>()
.AddEntityFrameworkStores<ApplicationDbContext>();
```
這兩行代碼都是
IdentityBuilder
的成員方法
```
public virtual IdentityBuilder AddRoles<TRole>() where TRole : class
{
RoleType = typeof(TRole);
AddRoleValidator<RoleValidator<TRole>>();
Services.TryAddScoped<RoleManager<TRole>, RoleManager<TRole>>();
return this;
}
```
```
public virtual IdentityBuilder AddClaimsPrincipalFactory<TFactory>() where TFactory : class
{
return AddScoped(typeof(IUserClaimsPrincipalFactory<>).MakeGenericType(UserType), typeof(TFactory));
}
```
5. 寫這個主要是為了給自己提個醒,有什麼不了解的可以直接郵箱我