Skip to content

Commit aa575a8

Browse files
author
Simon Mulser
committed
wait for token if not available
1 parent fb2c7aa commit aa575a8

File tree

1 file changed

+31
-14
lines changed

1 file changed

+31
-14
lines changed

projects/lib/src/interceptors/default-oauth.interceptor.ts

+31-14
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
11
import { Injectable, Optional } from '@angular/core';
2-
import { OAuthStorage } from '../types';
2+
import { OAuthService } from '../oauth-service';
33
import {
44
HttpEvent,
55
HttpHandler,
66
HttpInterceptor,
77
HttpRequest,
88
} from '@angular/common/http';
9-
import { Observable } from 'rxjs';
10-
import { catchError } from 'rxjs/operators';
9+
import { Observable, of, merge } from 'rxjs';
10+
import { catchError, filter, map, take, mergeMap, timeout } from 'rxjs/operators';
1111
import { OAuthResourceServerErrorHandler } from './resource-server-error-handler';
1212
import { OAuthModuleConfig } from '../oauth-module.config';
1313

14+
const WAIT_FOR_TOKEN_RECEIVED = 1000;
15+
1416
@Injectable()
1517
export class DefaultOAuthInterceptor implements HttpInterceptor {
1618
constructor(
17-
private authStorage: OAuthStorage,
19+
private oAuthService: OAuthService,
1820
private errorHandler: OAuthResourceServerErrorHandler,
1921
@Optional() private moduleConfig: OAuthModuleConfig
2022
) { }
@@ -42,17 +44,32 @@ export class DefaultOAuthInterceptor implements HttpInterceptor {
4244

4345
const sendAccessToken = this.moduleConfig.resourceServer.sendAccessToken;
4446

45-
if (sendAccessToken && this.authStorage.getItem('access_token')) {
46-
const token = this.authStorage.getItem('access_token');
47-
const header = 'Bearer ' + token;
48-
49-
const headers = req.headers.set('Authorization', header);
50-
51-
req = req.clone({ headers });
47+
if (!sendAccessToken) {
48+
return next
49+
.handle(req)
50+
.pipe(catchError(err => this.errorHandler.handleError(err)));
5251
}
5352

54-
return next
55-
.handle(req)
56-
.pipe(catchError(err => this.errorHandler.handleError(err)));
53+
return merge(
54+
of(this.oAuthService.getAccessToken()).pipe(
55+
filter(token => token ? true : false),
56+
),
57+
this.oAuthService.events.pipe(
58+
filter(e => e.type === 'token_received'),
59+
timeout(WAIT_FOR_TOKEN_RECEIVED),
60+
map(_ => this.oAuthService.getAccessToken()),
61+
),
62+
).pipe(
63+
take(1),
64+
mergeMap(token => {
65+
const header = 'Bearer ' + token;
66+
const headers = req.headers.set('Authorization', header);
67+
req = req.clone({ headers });
68+
69+
return next
70+
.handle(req)
71+
.pipe(catchError(err => this.errorHandler.handleError(err)));
72+
}),
73+
);
5774
}
5875
}

0 commit comments

Comments
 (0)