且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 IdentityServer4 中为访问令牌添加自定义声明?

更新时间:2022-12-11 15:24:23

你应该实现你自己的 ProfileService.看看我在实现相同时遵循的这篇文章:

You should implement your own ProfileService. Have a look in this post which I followed when I implemented the same:

https://damienbod.com/2016/11/18/extending-identity-in-identityserver4-to-manage-users-in-asp-net-core/

这是我自己的实现示例:

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>();