我正在尝试了解有关Identity Server的更多信息。我目前正在努力让基于角色的授权发挥作用。以下是我所遵循的步骤:
1( 下载示例解决方案:https://github.com/IdentityServer/IdentityServer4.Samples/tree/release/Quickstarts/6_AspNetIdentity
2( 运行解决方案,启动:
a( Identity Server项目
b( MVC项目
c( API项目
3( 浏览到MVC项目并应用迁移。4( 注册新用户:Bert@Bert.com5( 浏览到MVC项目中的CallApiUsingUserAccessToken。API已按预期到达,因为用户已获得授权。
假设我现在想从以下内容更改IdentityContoller:
[Authorize]
public class IdentityController : ControllerBase
到此:
[Authorize(Roles="Admin")]
public class IdentityController : ControllerBase
和家庭控制器(https://github.com/IdentityServer/IdentityServer4.Samples/blob/release/Quickstarts/6_AspNetIdentity/src/MvcClient/Controllers/HomeController.cs)来自:
public async Task<IActionResult> CallApiUsingUserAccessToken()
到此:
[Authorize(Roles="Admin")]
public async Task<IActionResult> CallApiUsingUserAccessToken()
我必须对配置进行哪些更改?
今天下午我试了几个建议。例如,在MVCClient的启动中,我尝试添加:
options.ClaimActions.MapJsonKey("role", "role", "role");
options.TokenValidationParameters.NameClaimType = "name";
options.TokenValidationParameters.RoleClaimType = "role";
请假设我已正确地将角色添加到身份数据库中(并将角色与用户关联(。
您想要的是AddProfileService()
方法,您可以在其中添加IProfileService接口的自定义实现,您可以自定义要添加到访问令牌的声明。
下面是一个使用Identity的示例,它将角色声明添加到令牌中
public class ProfileService : IProfileService
{
protected UserManager<ApplicationUser> _userManager;
public ProfileService(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var user = await _userManager.GetUserAsync(context.Subject);
var roles = await _userManager.GetRolesAsync(user);
var claims = new List<Claim>
{
new Claim(JwtClaimTypes.Role, roles.Any() ? roles.First() : "Standard")
};
context.IssuedClaims.AddRange(claims);
}
public async Task IsActiveAsync(IsActiveContext context)
{
var user = await _userManager.GetUserAsync(context.Subject);
context.IsActive = (user != null) && user.LockoutEnabled;
}
}
然后在启动时,告诉idp使用您的类
var builder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
})
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddAspNetIdentity<ApplicationUser>()
.AddProfileService<ProfileService>();