Custom claims in ASP.NET Core 2 web app

I have code based on the sample https://github.com/okta/samples-aspnetcore/tree/master/okta-hosted-login. I would like to add custom claims to the ClaimsPrincipal and have them persisted in the auth cookie. Is there an event hook in the authentication process where I can do this?

I’ve seen the example using IClaimsTransformation, but that transformation happens on each request. I only want to perform the logic once when the user logs in.

I’ve seen examples using OpenId Connect where there is an OnTokenValidated event, but I don’t see how to integrate that into this okta code.

This is old enough OP may not benefit. But I ran into the same problem where some profile info doesn’t make it into the User. The following modifications worked for me and does only run on initial login. Hopefully this saves others time…

.AddOktaMvc(new OktaMvcOptions()
            {
                OktaDomain = Configuration.GetValue<string>("Okta:OktaDomain"),
                ClientId = Configuration.GetValue<string>("Okta:ClientId"),
                ClientSecret = _oktaClientSecret,
                Scope = new List<string> { "openid", "profile", "email" },

                OnTokenValidated = async ctx =>
                {
                    var user = ctx.Principal;                    
                    var email = user.Claims.FirstOrDefault(claim => claim.Type == "email").Value;

                    var okta = ctx.HttpContext.RequestServices.GetRequiredService<IOktaClient>();
                    var oktaUser = await okta.Users.GetUserAsync(email);
                    var org = oktaUser.Profile.GetProperty<string>("organization");

                    var claims = new List<Claim> { new Claim("organization", org) };
                    user.AddIdentity(new ClaimsIdentity(claims));                    
                }
            })

Is this possible in the .AddOpenIdConnect portion within Startup.cs?

I have my .net core 2.2 app logging in directly without a sign-in screen, but I wanted to add a couple custom claims pulled from a database table.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.