Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: only add token to header if user is logged in #164

Merged
merged 1 commit into from
Oct 9, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
HttpEvent
} from '@angular/common/http';

import { Observable } from 'rxjs';
import { Observable, from } from 'rxjs';
import { mergeMap } from 'rxjs/operators';

import { KeycloakService } from '../services/keycloak.service';
Expand Down Expand Up @@ -53,7 +53,7 @@ export class KeycloakBearerInterceptor implements HttpInterceptor {

/**
* Intercept implementation that checks if the request url matches the excludedUrls.
* If not, adds the Authorization header to the request.
* If not, adds the Authorization header to the request if the user is logged in.
*
* @param req
* @param next
Expand All @@ -73,6 +73,23 @@ export class KeycloakBearerInterceptor implements HttpInterceptor {
return next.handle(req);
}

return from(this.keycloak.isLoggedIn()).pipe(
mergeMap((loggedIn: boolean) => loggedIn
? this.handleRequestWithTokenHeader(req, next)
: next.handle(req))
);
}

/**
* Adds the token of the current user to the Authorization header
*
* @param req
* @param next
*/
private handleRequestWithTokenHeader(
req: HttpRequest<any>,
next: HttpHandler
): Observable<any> {
return this.keycloak.addTokenToHeader(req.headers).pipe(
mergeMap(headersWithBearer => {
const kcReq = req.clone({ headers: headersWithBearer });
Expand Down