Skip to content

Instantly share code, notes, and snippets.

@minhlucvan
Created December 29, 2017 02:16
Show Gist options
  • Select an option

  • Save minhlucvan/63ae55990dd309ab49f9e17115379362 to your computer and use it in GitHub Desktop.

Select an option

Save minhlucvan/63ae55990dd309ab49f9e17115379362 to your computer and use it in GitHub Desktop.
Angular2 - Keycloak
import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {AuthGuard} from './shared/services/auth.guard';
import {HomeComponent} from './home/home.component';
export const routes: Routes = [
{
path: ':realm', canActivate: [AuthGuard],
children: [
{path: '', redirectTo: 'home', pathMatch: 'full'},
{path: 'home', component: HomeComponent}
]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router} from '@angular/router';
import {UserService} from './user.service';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private user: UserService) {
}
canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
const realm = route.paramMap.get('realm');
return this.user.isLoggedIn(realm);
}
}
import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {Keycloak} from '@ebondu/angular2-keycloak';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(private keycloak: Keycloak) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = this.keycloak.accessToken;
if (token) {
const authReq = req.clone({setHeaders: {Authorization: `Bearer ${token}`}});
return next.handle(authReq);
} else {
return next.handle(req);
}
}
}
import {Injectable} from '@angular/core';
import {Keycloak, KeycloakAuthorization} from '@ebondu/angular2-keycloak';
import {Observable} from 'rxjs/Observable';
import {Http} from '@angular/http';
@Injectable()
export class UserService {
constructor(private http: Http, private keycloak: Keycloak, private keycloakAuthz: KeycloakAuthorization) {
}
isLoggedIn(realm): Observable<boolean> {
if (this.keycloak.accessToken) {
return Observable.of(true);
} else {
this.keycloak.config = {
realm, 'auth-server-url': 'http://localhost:4200/auth', 'ssl-required': 'external',
resource: 'app-ui', 'public-client': true
};
this.keycloakAuthz.init();
this.keycloak.init({flow: 'standard', responseMode: 'fragment', checkLoginIframe: true, onLoad: 'login-required'});
return Keycloak.authenticatedObs.take(2).filter(auth => auth === true);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment