Issue
I’m trying to set up jwt
authentication with refresh token
. I have this method in my authenticationService
:
isAuthenticated(): boolean {
const jwtHelper = new JwtHelperService();
return !jwtHelper.isTokenExpired(this.getAccessToken());
}
And I want to use it like this:
isAuthenticated(): Observable<boolean> {
const jwtHelper = new JwtHelperService();
if (!jwtHelper.isTokenExpired(this.getAccessToken())) {
return of(true);
}
return this.refreshToken(); // returns Observable<boolean>
}
So, I want always to have valid access token instead of refreshing it on each api call (which is probably better) because I use it in *ngIf
to not show some component if user is not logged in. So, how to do a one call to refreshToken
for all calls to isAuthenticated
?
Solution
So, I decided to use flow from this post. I added app initialzer
(which call refreshToken
) and replaced isAuthenticated
with
isAuthenticated(): boolean {
return this.gerUserData() != null;
}
I think this flow is better because refreshing token every time when it’s expired is useless without api calls with payload.