Search code examples
c#asp.net-coreoauth-2.0openididentityserver4

How to add custom claims to access token in IdentityServer4?


I am using IdentityServer4.

I want to add other custom claims to access token but I'm unable to do this. I have modified Quickstart5 and added ASP.NET Identity Core and the custom claims via ProfileService as suggested by Coemgen below.

You can download my code here: [zip package][3]. (It is based on: Quickstart5 with ASP.NET Identity Core and added claims via ProfileService).

Issue: GetProfileDataAsync does not execute.


Solution

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

    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;
        }
    }
    

    Don't forget to configure the service in your Startup.cs (via this answer)

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