Search code examples
asp.net-coreasp.net-web-apiasp.net-identityidentityserver4

Add Role in Identity Core Token Response for ASP.NET Core SPA Template


So I'm using the ASP.NET Core React Template with built-in authorization. In that template, everything is working and I'm able to login and register an account via this

services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

services.AddIdentityServer()
    .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

services.AddAuthentication()
    .AddIdentityServerJwt();

When I view the token via application localstorage, I get the following data. Without the role. enter image description here

I also viewed the access token via jwt.io

My question is, how can I add the role there or the role in the jwt token?

Thank you!


Solution

  • You need to create a ProfileService which implements IProfileService interface

    I share you code from my project

    public class ProfileService : IProfileService
    {
        protected UserManager<ApplicationUser> UserManager;
        public ProfileService(UserManager<ApplicationUser> userManager)
        {
            UserManager = userManager;
        }
    
        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            ApplicationUser user = await UserManager.GetUserAsync(context.Subject);
    
            IList<string> roles = await UserManager.GetRolesAsync(user);
    
            var claims = new List<Claim> {
                // here you can include other properties such as id, email, address, etc. as part of the jwt claim types
                new Claim(JwtClaimTypes.Email, user.Email),
                new Claim(JwtClaimTypes.Name, $"{user.Firstname} {user.Lastname}")
            };
            foreach (string role in roles)
            {
                // include the roles
                claims.Add(new Claim(JwtClaimTypes.Role, role));
            }
    
            context.IssuedClaims.AddRange(claims);
        }
    
        public Task IsActiveAsync(IsActiveContext context)
        {
            return Task.CompletedTask;
        }
    }
    

    Add DI registration to Startup

    services.AddTransient<IProfileService, ProfileService>();
    

    Details in IdentityServer4 documentation