ssilvert / keycloak-schematic

Schematic to add Keycloak support Angular CLI applications
Apache License 2.0
31 stars 5 forks source link

Interceptor #5

Open rafaelvicio opened 6 years ago

rafaelvicio commented 6 years ago

How can I register this interceptor in my application?

ssilvert commented 6 years ago

I'm not sure I understand your question. What is "this"?

Usage instructions are in the wiki: https://github.com/ssilvert/keycloak-schematic/wiki

rafaelvicio commented 6 years ago

I am trying to register the interceptor: KeycloakHttp in my application but I am getting the following error:

Error: StaticInjectorError(AppModule)[InjectionToken HTTP_INTERCEPTORS -> ConnectionBackend]: StaticInjectorError(Platform: core)[InjectionToken HTTP_INTERCEPTORS -> ConnectionBackend]: NullInjectorError: No provider for ConnectionBackend! Stack trace:

app.module.ts:

import { BrowserModule } from '@angular/platform-browser'; import { NgModule, APP_INITIALIZER } from '@angular/core'; import { RouterModule } from '@angular/router';

import { HttpModule } from '@angular/http'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { FrontlineModule } from './frontline/frontline.module'; import { SisegModule } from './siseg/siseg.module';

import { AppComponent } from './app.component'; import { HomeComponent } from './home/home.component'; import { IndexComponent } from './index/index.component'; import { AppRoutingModule } from './app.routing.module'; import { KeycloakService } from './siseg/keycloak-service/keycloak.service';

import { KeycloakHttp } from './siseg/keycloak-service/keycloak.http';

@NgModule({ declarations: [ AppComponent, HomeComponent, IndexComponent ], imports: [ BrowserModule, FrontlineModule, SisegModule, RouterModule, HttpModule, HttpClientModule, AppRoutingModule ], providers: [ KeycloakService, { provide: HTTP_INTERCEPTORS, useClass: KeycloakHttp, multi: true } ], bootstrap: [AppComponent] }) export class AppModule { }

pablobastidasv commented 6 years ago

Hello @rafaelvicio, based on this post I created my own Interceptor over HttpClient

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';

import { KeycloakService } from './keycloak.service';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor(public _keycloakService: KeycloakService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if(this._keycloakService.authenticated()){
      return this.handleSecureRequest(request, next);
    } else {
      return next.handle(request)
    }
  }

  handleSecureRequest(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const tokenPromise: Promise<string> = this._keycloakService.getToken();
    const tokenObservable: Observable<string> = Observable.fromPromise(tokenPromise);

    return tokenObservable.map(token => {
        request = request.clone({
          setHeaders: {
            Authorization: `Bearer ${token}`
          }
        });

        return request;
      }).concatMap(req => next.handle(req));
  }
}

And then added to the module


  providers: [
    ...
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    },
    ...

Hopefully this works for you also

giovannicandido commented 6 years ago

If you are on angular 4 or using Http, which have no build in support for interceptors check this project: https://github.com/giovannicandido/angular-http-interceptor/blob/master/README.md And then check this interceptor: https://github.com/giovannicandido/angular-spa/blob/master/src/auth/interceptors/refresh-token-http-interceptor.ts

By the way angular-spa is reusable.