In ASP.NET core Azure AD implementation, there are some custom logic coded under the OnTokenValidated
event, which is called whenever the user logging in successfully. But the problem here is, OnTokenValidated
is not called every time, it bypassed silently due to SSO. I've checked all the other events as well (like OnTicketReceived
, OnAuthorizationCodeReceived
etc) they also not fired as well. The only way I can fire it up is clear all the browser cache. So my question is how to execute that custom logic code available under OnTokenValidated
event once the user signed in using SSO?
Any help appreciated. Thank you.
EDIT: Here is the code i tried...
builder.Services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.Events = new OpenIdConnectEvents
{
// Event triggered before redirecting to Azure AD
OnRedirectToIdentityProvider = context =>
{
Console.WriteLine("Redirecting to Azure AD...");
return Task.CompletedTask;
},
// Event triggered after token validation but NOT in SSO
OnTokenValidated = context =>
{
Console.WriteLine($"Token validated for user: {context.Principal.Identity.Name}");
// Add custom claims or other logic
var identity = (ClaimsIdentity)context.Principal.Identity;
identity.AddClaim(new Claim("CustomClaim", "CustomValue"));
return Task.CompletedTask;
},
// Event triggered when authentication fails
OnAuthenticationFailed = context =>
{
Console.WriteLine($"Authentication failed: {context.Exception.Message}");
context.Response.Redirect("/Error");
context.HandleResponse(); // Stop further processing
return Task.CompletedTask;
},
**// Event triggered when an authorization code is received**
OnAuthorizationCodeReceived = context =>
{
Console.WriteLine("Authorization code received.");
return Task.CompletedTask;
}
};