Skip to content

ymombrun/angular2-keycloak

 
 

Repository files navigation

angular2-keycloak

Native Typescript Keycloak library for angular2/4.

Installation

To install this library, run:

$ npm install @ebondu/angular2-keycloak --save

Development

To generate all *.js, *.js.map and *.d.ts files:

$ npm run tsc

To lint all *.ts files:

$ npm run lint

Usage

Declare Keycloak module in angular app :

import { Ng2KeycloakModule } from '@ebondu/angular2-keycloak';
...

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    Ng2KeycloakModule
  ],
  providers: [
    ...
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

To login

import { Keycloak } from '@ebondu/angular2-keycloak';
...

export class MyLoginClass implements OnInit {

  public parsedToken: any;
  public isAuthenticated: boolean;
  public profile: any;

  constructor( private keycloak: Keycloak) {
    Keycloak.authenticatedObs.subscribe(auth => {
      this.isAuthenticated = auth;
      this.parsedToken = Keycloak.tokenParsed;

      console.info('APP: authentication status changed...');
    });
    this.keycloak.init({});
  }

  ngOnInit() {
    // Configure the Keycloak
    Keycloak.config = 'assets/keycloak.json';

    // Initialise the Keycloak
    this.keycloak.init({
      checkLoginIframe: false
    });
  }

  login() {
    Keycloak.login({});
  }

  logout() {
    Keycloak.logout({});
  }

  loadProfile() {
    Keycloak.loadUserProfile().subscribe(profile => {
      this.profile = profile;
    });
  }

  ...
}

Please, use Http interface to get access to Keycloak http proxy (authentication / authorization). Angular will inject the right provider class for you.

import { Http } from '@angular/http';
...

@Injectable()
export class MyClass {
    // Angualar will inject the instance of the KeycloakHttp class
    constructor(private http: Http) {}

    callAPI(): Observable<MyObject> {

      let headers = new Headers({'Accept' :'application/json'});
      let options: RequestOptionsArgs = { headers: headers };
        return this.http.get("http://localhost/myAPI/myMethod",  options)
            .map(res => res.json())
            .catch(err => handleError(err));
     }
     ...
}

Example

See angular2-webpack-product-app

License

Apache2 © ebondu

angular2-keycloak

About

Angular 2 Keycloak client wrapper

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 83.0%
  • JavaScript 14.7%
  • HTML 1.4%
  • CSS 0.9%