I'm facing an issue with validating the AccessToken received from Microsoft in my Angular 16 frontend application using MSAL 3 for authentication. Although I can successfully obtain the tokens, I'm encountering problems when it comes to validating the AccessToken. Strangely, I can validate the idToken without any issues, but the AccessToken appears to be invalid, even when checked on jwt.io.
To address this problem, I have implemented a custom HTTP interceptor that utilizes msal.instance.silentAcquire(...) to retrieve the idToken and create a new HTTP header with the token. While this approach works, it doesn't feel clean and results in messy code.
I would appreciate any insights or explanations as to why I'm unable to validate the AccessToken.
Thank you in advance for your help!
For a little bit more unterstanding: Angular Frontend gets Token via MSAL, calls Spring Boot API with Token, Backend validate Token and give response if token is valid.
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpErrorResponse,
HttpStatusCode,
} from '@angular/common/http';
import { Observable, catchError, from, mergeMap, throwError } from 'rxjs';
import { MsalService } from '@azure/msal-angular';
import { SilentRequest } from '@azure/msal-browser';
@Injectable()
export class HttpInterceptor implements HttpInterceptor {
constructor(private authService: MsalService) { }
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
if (request.url.includes('localhost:8080')) {
const headerConf = {
Authorization: '',
'Content-Type': 'application/json',
Accept: 'application/json',
};
const silentRequest: SilentRequest = {
scopes: ['user.read'],
};
return from(this.authService.instance.acquireTokenSilent(silentRequest)).pipe(
mergeMap((data) => {
const idToken = data.idToken;
headerConf.Authorization = `Bearer ${idToken}`;
const req = request.clone({ setHeaders: headerConf });
return next.handle(req);
}),
catchError((err) => {
const error = err as HttpErrorResponse;
if (error.status == HttpStatusCode.Forbidden) {
console.error("Fehler beim request", error);
}
return throwError(() => new Error(err));
})
);
} else {
return next.handle(request);
}
}
}
Validate AccessToken on jwt.io, created an api expose in azure, tried several key and issuer configs in spring boot
I created an Azure AD Application and granted API permissions like below:
I generated Access and ID tokens by using below parameters via Postman:
https://login.microsoftonline.com/TenantID/oauth2/v2.0/token
client_id:ClientID
grant_type:authorization_code
scope:user.read profile openid
code:code
redirect_uri:https://jwt.ms
client_secret:ClientSecret
ID token got validated successfully like below:
But Access token dint get validated and got an error like below:
The "invalid token" error occurs due to many reasons like if the access token is expired or passing wrong scope or aud
is invalid.
Force your application to acquire new access token regularly and set the value to true
.
result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
.WithForceRefresh(true)
.ExecuteAsync();
Refer this SO Thread by me for more in detail.
Note that: If you are generating the access token for Microsoft Graph, then there is no need to validate the access token.
I generated the access token for the Web API:
scope: api://xxxx/test.read
Now, the access token validated successfully like below: