- 参考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. 写这个主要是为了给自己提个醒,有什么不理解的可以直接邮箱我