asp.net-coremicrosoft.identity.web

OnTokenValidated event not triggered


What I'm trying to do is add a claim after authentication. The following example of triggering an OnTokenValidation event not actually working.

I'm using Microsoft.Identity.Web to authenticate on Azure AD. That part works! How can I register events using AddMicrosoftIdentityWebAppAuthentication to add custom claims

services.AddMicrosoftIdentityWebApiAuthentication(_configuration);
services.Configure<MicrosoftIdentityOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
            {
                options.Events = new OpenIdConnectEvents
                {
                    OnTokenValidated = ctx =>
                    {
                        var claims = new List<Claim> {
                            new Claim(ClaimTypes.OtherPhone, "somevalue")
                        };
                        ctx.Principal.AddIdentity(new ClaimsIdentity(claims));
                        return Task.CompletedTask;
                    },
                };
            });

Solution

  • You are using AddMicrosoftIdentityWebApiAuthentication, so the events that will be triggered are JwtBearerEvents.

    You can set them up as below (.NET 6 API):

    // Add services to the container.
    builder.Services
        .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApi(builder.Configuration);
    
    // Enable PII for logging
    IdentityModelEventSource.ShowPII = true;
    
    // Configure middleware events
    builder.Services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
    {
        options.Events = new JwtBearerEvents
        {
            OnTokenValidated = ctx =>
            {
                var accessToken = ctx.SecurityToken;
                Debug.WriteLine("[OnTokenVaidated]: I can do stuff here! ");
                return Task.CompletedTask;
            },
            OnMessageReceived = ctx =>
            {
                Debug.WriteLine("[OnMessageReceived]: I can do stuff here! ");
                return Task.CompletedTask;
            },
            OnAuthenticationFailed = ctx =>
            {
                Debug.WriteLine("[OnAuthenticationFailed]: Authentication failed with the following error: ");
                Debug.WriteLine(ctx.Exception);
                return Task.CompletedTask;
            },
            OnChallenge = ctx =>
            {
                Debug.WriteLine("[OnChallenge]: I can do stuff here! ");
                return Task.CompletedTask;
            }
        };
    });