Farman Saifi
Farman Saifi

Reputation: 1

return user role in token response using CustomTokenRequestValidationContext in identity server 4

I am using Identity Server 4.0 with Identity Core, I need user role along with token response.

below attached image for reference

Upvotes: 0

Views: 187

Answers (1)

Myte
Myte

Reputation: 51

It is not the correct concept due to OAuth2 protocol violation and requires modifying the internals of IS4.

But you could implement getting role from: - User info endpoint (http://docs.identityserver.io/en/3.1.0/endpoints/userinfo.html) - Access token

For the last variant, you should override profile service (http://docs.identityserver.io/en/3.1.0/reference/profileservice.html)|

For example:

public class MyProfileService  : IProfileService
    {
        private readonly UserManager<User> _userManager;

        public MyProfileService(UserManager<User> userManager)
        {
            _userManager = userManager;
        }

        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var user = await _userManager.GetUserAsync(context.Subject);
            var roles = await _userManager.GetRolesAsync(user);

            var claims = new List<Claim>
            {
                new Claim(JwtClaimTypes.Email, user.Email),
                new Claim(JwtClaimTypes.GivenName, user.FirstName),
                new Claim(JwtClaimTypes.FamilyName, user.LastName),
                new Claim(JwtClaimTypes.Name, $"{user.FirstName} {user.LastName}"),
                new Claim(JwtClaimTypes.Locale, user.PreferredLanguage)
            };
            claims.AddRange(roles.Select(role => new Claim(JwtClaimTypes.Role, role)));

            context.IssuedClaims.AddRange(claims);
        }

        public Task IsActiveAsync(IsActiveContext context)
        {
            context.IsActive = true;
            return Task.CompletedTask;
        }
    }

And don't forget to register it

            services.AddIdentityServer(options =>
            {
                ...
            })
            .AddProfileService<MyProfileService>()

Upvotes: 1

Related Questions