Search code examples
asp.net-coreazure-ad-b2cclaims

AzureADB2C.UI - access to OpenIdConnectEvents (OnTokenValidated)


I use the library AzureADB2C.UI to enable Azure ADB2C authentication.

But now I would like to add a custom claim after authentication and I wanted to do this during OpenIdConnectEvents.OnTokenValidated. But those events are not exposed.

Any suggestion what the most appropriate way is to add a custom claim in this situation? And preferable keep on using the package to avoid too much custom code. I tried the following on SO but this didn't work out.

Many thanks


Solution

  • You can refer to below code sample to add claims into user's principle :

    services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
                .AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options));
    
    services.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, options =>
    {
    
        options.Events = new OpenIdConnectEvents
        {
    
            OnTokenValidated =  ctx =>
            {
                //query the user's groups using api 
    
                // add claims
                var claims = new List<Claim>
                {
                    new Claim("groups", xxxx-xx-xx)
                };
                var appIdentity = new ClaimsIdentity(claims);
    
                ctx.Principal.AddIdentity(appIdentity);
    
                return Task.CompletedTask;
            },   
        };
    });