Search code examples
.net-coreidentityserver4asp.net-core-3.1

Adding custom claims (for authorization) to Principal on Client side


I have been able to successfully implement my own IdentityServer4 authentication server on .net core 3.1 and I have a client web application connecting to it. The client is successfully receiving an access token and an id. The token contains all the user identifying information.

My next objective is to add the privileges that the user has within the client to the HttpContext.User as claims right after I get the token before any other page is rendered. The privileges are stored in the database associated to a user by the subjectId.

I am in need of help on where to look to be able to add those claims so that my authorization policies can work with the claims in the principal. I would like the process to execute everytime a token is issued.

P.S. I am using a code flow for Identity server with GetClaimsFromUserInfoEndpoint = true and SaveTokens = true.

Thanks!


Solution

  • you can do this by using TokenValidated Event

        public class CustomJwtBearerEvents : JwtBearerEvents
    {
        public override async Task TokenValidated(TokenValidatedContext context)
        {
            var claims = context.Principal.Claims.ToList();
            claims.Add(new Claim("key", "value"));
            context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Bearer"));        }
    }
    

    Then register it in startup

            services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
                {
                  ...
                    options.Events = new JwtBearerEvents();
                    options.EventsType = typeof(CustomJwtBearerEvents);
                });