I have an application API aspnet core 6 and i configure to validate token that AzureAd with AddMicrosoftIdentityWebApi, below my code.
At the API controller, i use [Authorize].
This code at the Program.cs
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
builder.Services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
{
string _tenant = "MY-TENANT-ID";
string _clientId = "MY-CLIENT-ID";
IList<string> validissuers = new List<string>()
{
$"https://login.microsoftonline.com/{_tenant}/",
$"https://login.microsoftonline.com/{_tenant}/v2.0",
$"https://login.windows.net/{_tenant}/",
$"https://login.microsoft.com/{_tenant}/",
$"https://sts.windows.net/{_tenant}/"
};
IList<string> validaudiences = new List<string>()
{
$"api://{_clientId}",
$"{_clientId}"
};
var existingOnTokenValidatedHandler = options.Events.OnTokenValidated;
options.Events.OnTokenValidated = async context =>
{
await existingOnTokenValidatedHandler(context);
//options.TokenValidationParameters.ValidateIssuerSigningKey = true;
options.TokenValidationParameters.ValidateLifetime = true;
// Your code to add extra configuration that will be executed after the current event implementation.
options.TokenValidationParameters.ValidIssuers = validissuers;
options.TokenValidationParameters.ValidateIssuer = true;
options.TokenValidationParameters.ValidAudiences = validaudiences;
options.TokenValidationParameters.ValidateAudience = true;
};
});
enter image description here - post by insomnia