isAuthenticated observable is false when localStorage is used
jwoyame opened this issue · 3 comments
Thank you for this excellent sample.
The isAuthenticated
observable produces a correct value when logging in or after a silent refresh. However, it doesn't seem there is any event to update the value when the application first loads and there is already a valid access token available in localStorage.
Current code:
this.oauthService.events
.subscribe(_ => {
this.isAuthenticatedSubject$.next(this.oauthService.hasValidAccessToken());
});
Proposed fix:
this.oauthService.events
.subscribe(_ => {
this.isAuthenticatedSubject$.next(this.oauthService.hasValidAccessToken());
});
// see if already logged in
this.isAuthenticatedSubject$.next(this.oauthService.hasValidAccessToken());
Interesting! Thanks for your suggestion. At first glance this seems like a nice improvement! Will try to look at it somewhere during the week, a bit busy at work at the moment.
I just want to clarify exactly what caused my issue to justify the above added line.
It sometimes works fine, where isAuthenticated
is correctly true, and other times doesn't detect that the user is already authenticated.
It turned out that it was incorrectly false only right after I log in.
I traced this to the fact that if the timeoutFactor
on the access token is exceeded, then the setupAccessTokenTimer
function would trigger an event, and this would cause this line to run in the sample:
this.isAuthenticatedSubject$.next(this.oauthService.hasValidAccessToken());
However, if the token is not old enough for the token timer to fire when the page is loaded, there are no events at all that would trigger this code to run. The fix was to add this line to make sure it always runs initially when the app is loaded.
Thx for the fix! I've added some tests and merged your PR.