Skip to content

Commit 040ab71

Browse files
authored
fix(keycloak): do not add authorization header on unauthenticated (#101)
Closes #95
1 parent 74f34cb commit 040ab71

File tree

1 file changed

+31
-11
lines changed

1 file changed

+31
-11
lines changed

projects/sbb-esta/angular-keycloak/src/lib/auth/auth.service.ts

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,27 @@ export class AuthService {
1515
@Inject(KEYCLOAK_LOGIN_OPTIONS) @Optional() private _loginOptions: KeycloakLoginOptions = {}
1616
) {}
1717

18+
/**
19+
* Redirects to login form.
20+
* @param options Login options.
21+
*/
1822
login(options?: KeycloakLoginOptions): Promise<void> {
1923
const loginOptions = Object.assign({}, this._loginOptions, options);
2024
return this._toNativePromise(this.keycloak.login(loginOptions));
2125
}
2226

27+
/**
28+
* Redirects to logout.
29+
* @param options Logout options.
30+
* @param options.redirectUri Specifies the uri to redirect to after logout.
31+
*/
2332
logout(options?: any): Promise<void> {
2433
return this._toNativePromise(this.keycloak.logout(options));
2534
}
2635

36+
/**
37+
* Is true if the user is authenticated, false otherwise.
38+
*/
2739
authenticated(): boolean {
2840
return this.keycloak.authenticated;
2941
}
@@ -37,28 +49,36 @@ export class AuthService {
3749
return this._toNativePromise(this.keycloak.updateToken(minValidity));
3850
}
3951

52+
/**
53+
* Returns the current token.
54+
*/
4055
getToken(): string {
4156
return this.keycloak.token;
4257
}
4358

59+
/**
60+
* Returns an instance of HttpHeaders with the Authorization entry
61+
* or an empty instance of HttpHeaders, if the token is not available.
62+
*/
4463
getAuthHeader(): HttpHeaders {
4564
const authToken = this.getToken();
46-
return new HttpHeaders().set('Authorization', `Bearer ${authToken}`);
65+
return authToken
66+
? new HttpHeaders().set('Authorization', `Bearer ${authToken}`)
67+
: new HttpHeaders();
4768
}
4869

70+
/**
71+
* Returns or loads the user profile information.
72+
* If no user is authenticated, returns an observable of undefined.
73+
*/
4974
getUserInfo(): Observable<KeycloakProfile | undefined> {
50-
if (!this.authenticated() || this.keycloak.profile) {
75+
if (!this.authenticated()) {
76+
return of(undefined);
77+
} else if (this.keycloak.profile) {
5178
return of(this.keycloak.profile);
79+
} else {
80+
return from(this._toNativePromise(this.keycloak.loadUserProfile()));
5281
}
53-
54-
return from(
55-
new Promise((resolve, reject) => {
56-
this.keycloak
57-
.loadUserProfile()
58-
.success(resolve)
59-
.error(err => reject(err));
60-
})
61-
);
6282
}
6383

6484
private _toNativePromise<TSuccess, TError>(

0 commit comments

Comments
 (0)