Open Closed

IdentityServer: How to customize jwt token generation #300


User avatar
0
danghung created

We have a project that has been using aspnetzero. UserId is long type. Now I will start new project with abp.io, I want to use Guid as UserId.

Both project have to be same user, password, etc. Authentication server will be used abp.io, I will add new externalUserId field to User table ( it is Id in User table aspnetzero)

Identity Server generate jwt token, it contains "sub": Guid If user login from aspnetzero project ( identified by domain or clientId ), I have to customize jwt token to generate "sub" : externalUserId.

Futhermore, in aspnetzero project. I can add custimze field to jwt token by add CustomProfileService like that.

public class CustomProfileService<TUser> : IProfileService where TUser : AbpUser<TUser>
{
    [UnitOfWork]
    public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        var tenantId = context.Subject.Identity.GetTenantId();
        using (_unitOfWorkManager.Current.SetTenantId(tenantId))
        {
            var sub = context.Subject.GetSubjectId();
            var user = await _userManager.FindByIdAsync(sub);
            var principal = await _claimsFactory.CreateAsync(user);
            var claims = principal.Claims.ToList();
            claims = claims.Where(claim => context.RequestedClaimTypes.Contains(claim.Type)).ToList();
            var abpUser = user as User;
            claims.Add(new Claim("user_email", user.EmailAddress ?? string.Empty));
            claims.Add(new Claim("CompanyId", abpUser.CompanyId.HasValue ? abpUser.CompanyId.ToString() : string.Empty));
            claims.Add(new Claim("UserExternalId", abpUser.UserExternalId ?? string.Empty));
            context.IssuedClaims = claims;
        }
    }
}

I don't know how to do that in abp.io. Please help me. Thank you.


1 Answer(s)
  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    Please see: https://github.com/abpframework/abp/issues/4388, https://github.com/abpframework/abp/issues/4350. They can help you.

Made with ❤️ on ABP v9.1.0-preview. Updated on December 13, 2024, 06:09