I have an AuthGuard which I want to check my authentication status in my App.
Simplified it should work like this:
- if there is an
access_cookie
, return true - if there is no
access_cookie
and norefresh_cookie
, return false - if there is no
access_cookie
, but arefresh_cookie
, request a newaccess_cookie
and on success, return true
However, returning plain true or false works of course, but the request for a new access_cookie
is an Observable<boolean>
.
My AuthGuard:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
...
const result = this.auth.checkCredentials(scopes);
console.log(result);
....
}
The checkCredentials()
(simplified):
checkCredentials(): boolean{
if (!this.cookieService.check('access_token')) {
if(this._getRefreshToken(){
try {
this.refresh().subscribe(
result=> {
return result;
},
error => {
return false;
});
} catch (e) {
return false;
}
}
}
return true;
}
The refresh
Obeservable
refresh(): Observable<boolean> {
if (this._getRefreshToken() && !this.cookieService.check('access_token')) {
const oauth2_token_endpoint = TOKEN_URL;
const headers = new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa(CLIENT_ID + ':' + CLIENT_SECRET),
});
const body = 'grant_type=' + GrantType.REFRESH + '&refresh_token=' + this._getRefreshToken();
return this.http.post<UserData>(oauth2_token_endpoint, body, {headers})
.pipe(map(user => {
if (user && user.access_token) {
this._saveToken(user);
return true;
}
return false;
}));
}
return throwError('Refresh Token Error');
}
The checkCredentials()
gets executed, but it does not wait for the refresh()
but instead returns undefined
immediately.
Where am I missing something?
I am using Angular 8.2.14 and rxjs 6.4.0