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

How to add custom claims to access token in IdentityServer4?

我正在使用 IdentityServer4

我想向访问令牌添加其他自定义声明,但我无法执行此操作。我修改了 Quickstart5 并按照 Coemgen .

的建议通过 ProfileService 添加了 ASP.NET Identity Core 和自定义声明

您可以在这里下载我的代码:[压缩包][3]。 (它基于:Quickstart5 和 ASP.NET Identity Core 并通过 ProfileService 添加声明)。

问题:未执行 GetProfileDataAsync。

您可以在配置 class 的 GetIdentityResources() 中使用 UserClaims 选项来包含任何声明:

用户声明: 应包含在身份令牌中的关联用户声明类型的列表。 (根据官方文档)http://docs.identityserver.io/en/release/reference/identity_resource.html#refidentityresource

您应该实现自己的 ProfileService。 看看这个 post ,我在实现相同时遵循了它:

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

这是我自己实现的一个例子:

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 中配置服务(通过

services.AddIdentityServer()
    .AddProfileService<ProfileService>();

发现问题。

在 startup.cs 中,不是添加 services.AddTransient<IProfileService, ProfileService>();,而是将 .AddProfileService<ProfileService>() 添加到 services.AddIdentityServer()

你最终会得到

services.AddIdentityServer()
    .AddTemporarySigningCredential()
    .AddInMemoryIdentityResources(Config.GetIdentityResources())
    .AddInMemoryApiResources(Config.GetApiResources())
    .AddInMemoryClients(Config.GetClients())
    .AddAspNetIdentity<ApplicationUser>()
    .AddProfileService<ProfileService>();

感谢 Coemgen 的帮助!代码没有问题,只是启动错误。

好的,这里的问题是:

虽然您已正确配置 可用 身份资源(标准和自定义),但您还需要明确定义 在调用您的api 资源。为了定义它,您必须转到 ExampleIdentityServer 项目上的 Config.cs class 并提供第三个参数,例如 new ApiResouirce 构造函数。只有那些将包含在 access_token

// scopes define the API resources in your system
public static IEnumerable<ApiResource> GetApiResources()
{
    return new List<ApiResource>
    {
        new ApiResource("api1", "My API", new[] { JwtClaimTypes.Subject, JwtClaimTypes.Email, JwtClaimTypes.Phone, etc... })
    };
}

本质上,这意味着我为我的组织配置了我的身份声明,但可能涉及多个 API,并且并非所有 API 都使用所有可用的配置文件声明。这也意味着这些将出现在您的 ClaimsPrincipal 中,其余的仍然可以通过“userinfo”端点作为正常的 http 调用访问。

注意:关于刷新令牌:

如果您选择通过 AllowOfflineAccess = true 启用刷新令牌,您可能会在刷新 access_token 时遇到相同的行为“GetProfileDataAsync 未执行!” .因此,access_token 中的声明保持不变,尽管您获得了具有更新生命周期的新 access_token。如果是这种情况,您可以通过在客户端配置上设置 UpdateAccessTokenClaimsOnRefresh=true 强制他们始终从配置文件服务刷新。