如何在 IdentityServer4 中为访问令牌添加自定义声明? [英] How to add custom claims to access token in IdentityServer4?
问题描述
我正在使用 IdentityServer4.
我想向访问令牌添加其他自定义声明,但我无法执行此操作.我修改了 Quickstart5 并按照 Coemgen 下面的建议通过 ProfileService 添加了 ASP.NET Identity Core 和自定义声明.
I want to add other custom claims to access token but I'm unable to do this. I have modified Quickstart5 and added ASP.NET Identity Core and the custom claims via ProfileService as suggested by Coemgen below.
你可以在这里下载我的代码:[zip package][3].(它基于:Quickstart5 和 ASP.NET Identity Core并通过 ProfileService 添加声明).
You can download my code here: [zip package][3]. (It is based on: Quickstart5 with ASP.NET Identity Core and added claims via ProfileService).
问题:未执行 GetProfileDataAsync.
Issue: GetProfileDataAsync does not executed.
推荐答案
你应该实现你自己的 ProfileService
.看看我在实现相同时遵循的这篇文章:
You should implement your own ProfileService
.
Have a look in this post which I followed when I implemented the same:
这是我自己的实现示例:
Here is an example of my own implementation:
public class ProfileService : IProfileService
{
protected UserManager<ApplicationUser> _userManager;
public ProfileService(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
//>Processing
var user = await _userManager.GetUserAsync(context.Subject);
var claims = new List<Claim>
{
new Claim("FullName", user.FullName),
};
context.IssuedClaims.AddRange(claims);
}
public async Task IsActiveAsync(IsActiveContext context)
{
//>Processing
var user = await _userManager.GetUserAsync(context.Subject);
context.IsActive = (user != null) && user.IsActive;
}
}
不要忘记在 Startup.cs 中配置服务(通过 这个答案)
Don't forget to configure the service in your Startup.cs (via this answer)
services.AddIdentityServer()
.AddProfileService<ProfileService>();
这篇关于如何在 IdentityServer4 中为访问令牌添加自定义声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!