我如何将计算字段添加到access_token / id_token

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我如何将计算字段添加到access_token / id_token相关的知识,希望对你有一定的参考价值。

我正在使用IdentityServer4,我想将计算字段添加到access_token / id_token。

这样的字段的示例可以是用户的IP(或令牌绑定散列),令牌将附加到该IP。

问:我怎么能这样做?

提前谢谢,对不好的英语抱歉。

答案

您可以通过在UserManager实现中创建方法来添加包含计算字段的声明。

public class UserManager: IUserManager
{
    ...other code here removed for simplicity

    public List<Claim> GetClaimsAsync(Models.User user)
    {
        var claims = new List<Claim>();             

        claims.Add(new Claim(JwtClaimTypes.PreferredUserName, user.USER_ID.ToString().Trim()));

        //This next line is pseudo coded and would need to be coded.
        claims.Add(new Claim("MyCalculatedIP", MyFunctionToGetUserIP().ToString().Trim()));


        return claims;
    }

    ...other code here removed for simplicity
}

从实现IProfileService的类中调用它。我命名我的ProfileService。

/// <summary>
///  implement the interface called "IProfileService", which is used for authorization.
/// </summary>
public class ProfileService : IProfileService
{
    IUserManager _myUserManager;
    private readonly ILogger<ProfileService> _logger;


    public ProfileService(ILogger<ProfileService> logger, IUserManager userManager)
    {
        _logger = logger;
        _myUserManager = userManager;
    }

    public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
    {            
        var user = await _myUserManager.Find(context.UserName, context.Password);

        if (user != null)
        {
            context.Result = new GrantValidationResult(
                             subject: user.USER_ID,
                             authenticationMethod: "custom",
                             claims: await _myUserManager.GetClaimsAsync(user));
        }
        else
        {                 
            context.Result = new GrantValidationResult(
                             TokenRequestErrors.InvalidRequest, 
                    errorDescription: "UserName or Password Incorrect.");
        }             
    }

    public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        _logger.LogDebug("Get profile called for {subject} from {client} with {claimTypes} because {caller}",
            context.Subject.GetSubjectId(),
            context.Client.ClientName,
            context.RequestedClaimTypes,
            context.Caller);

        var sub = context.Subject.FindFirst("sub")?.Value;
        if (sub != null)
        {
            var user = await _myUserManager.FindByNameAsync(sub);
            var cp = getClaims(user);

            var claims = cp.Claims;                

            context.IssuedClaims = claims.ToList();
        }
    }

    private ClaimsPrincipal getClaims(User user)
    {
        if (user == null)
        {
            throw new ArgumentNullException(nameof(user));
        }

        var id = new ClaimsIdentity();

        id.AddClaims(_myUserManager.GetClaimsAsync(user));

        return new ClaimsPrincipal(id);
    }

    /// <summary>
    /// Called by IdentityServer Middleware.
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public async Task IsActiveAsync(IsActiveContext context)
    {
        var sub = context.Subject.GetSubjectId();
        var user = await _myUserManager.FindByNameAsync(sub);
        context.IsActive = user != null;
        return;
    }
}

在Startup类中,为依赖注入添加ProfileService对象。

public void ConfigureServices(IServiceCollection services)
{
     ...other code here removed for simplicity

     Services.AddTransient<IProfileService, ProfileService>();

     ...other code here removed for simplicity
}

有用的来源artile

以上是关于我如何将计算字段添加到access_token / id_token的主要内容,如果未能解决你的问题,请参考以下文章

如何将计算字段添加到 Django 模型

如何获取accessToken

Pentaho:如何将字段(= 列)动态添加到 OutputRow?

SQL将计算列添加到表中

如何将计算字段映射到 JPA 实体?

如何在 access_token 中添加角色声明,目前它在 id_token 中?