[keycloak-dev] refactor angular2-product-app

Tair Sabirgaliev tair.sabirgaliev at gmail.com
Thu Feb 9 18:19:31 EST 2017


1. The KeycloakHttp implementation overrides all the http methods, but 
in the
Http class they all forward to 'request(...)' method, so overriding
`request(...)` should be enough.

2. It is not obvious why the implementation uses Observable.merge.
AFAICT the idea is to:

     (1) obtain the token (and update it BTW),
     (2) put it in header,
     (3) forward to superclass implementation.

So we found that the whole KeycloakHttp implementation could be reduced 
to the following:

@Injectable()
export class KeycloakHttp extends Http {
     constructor(_backend: ConnectionBackend, _defaultOptions: 
RequestOptions, _keycloakService: KeycloakService) {
         super(_backend, _defaultOptions);
     }

     request(url: string | Request, options?: RequestOptionsArgs): 
Observable<Response> {
         const tokenPromise: Promise<string> = 
this._keycloakService.getToken();
         const tokenObservable: Observable<string> = 
Observable.fromPromise(tokenPromise);

         if (typeof url === 'string') {
             return tokenObservable.map(token => {
                 const authOptions = new RequestOptions({
                     headers: new Headers({'Authorization': 'Bearer ' + 
token})
                 });
                 return new 
RequestOptions().merge(options).merge(authOptions);
             }).concatMap(opts => super.request(url, opts));
         } else if (url instanceof Request) {
             return tokenObservable.map(token => {
                 url.headers.set('Authorization', 'Bearer ' + token);
                 return url;
             }).concatMap(request => super.request(request));
         }
     }

}



More information about the keycloak-dev mailing list