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
CodePudding user response:
The error "invalid_token" occurs due to many reasons. In your scenario it might occur as you are passing old access token which is expired already.
To resolve the error, you must make sure that the access token isn't expired i.e refresh the access token.
I generated the access token by using parameters like below:
You can force your Application to acquire new access token regularly when value is set to true
.
result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
.WithForceRefresh(true)
.ExecuteAsync();
Note that: For security reasons MSAL.NET will not expose any refresh token and it refreshes the token with token cache.
- MSAL has a token cache and whenever token is generated it caches the token.
- MSAL also refreshes the token when the token is getting close to expire because the token cache contains a refresh token.
- Henceforth, there is no need of handling the token expiration on your own.
If still the error occurs, decode the generated token in jwt.io and check if the decode token contains the vaild aud
, iss
etc like below:
If you want to get the refresh token in the result, then generate the access token via Authorization code flow by passing offline_access
as the scope and refresh the access token.
Reference:
High availability AzureAD/microsoft-authentication-library-for-dotnet Wiki (github.com)