Disclaimer: This is non a tutorial on how to setup an Angular^4 project, nor are nosotros going to beak over how to setup a Keycloak server. Needless to say, y'all should already move familiar these tech earlier diving here.
I bring a previous article y'all may desire to cheque that discusses keycloak https://ngeblognow.blogspot.com//search?q=how-to-signin-to-keycloak-using-google.
After creating your customer inwards Keycloak, download the Keycloak OIDC JSON, nether Installation tab equally keycloak.json. We volition role it later.
Angular projection configuration (note I'm using version 4.4.3):
- Create your Angular project. I commonly role Angular CLI. I assume y'all are already familiar amongst Angular initial projection configuration.
- Put your keycloak.json within app/assets folder. This volition move eat yesteryear an angular service later.
- Install keycloak js
>npm install keycloak-js --save
- Step iii volition generate a keycloak.js within angular's node_modules folder. To role it nosotros involve to add together an entry inwards .angular-cli.json. Look for scripts department too add "../node_modules/keycloak-js/dist/keycloak.js"
- Now that nosotros bring the keycloak library on our project. We involve to practice the service that volition charge it.
import { Injectable } from '@angular/core'; import { surroundings } from 'environments/environment'; declare var Keycloak: any; @Injectable() export course of educational activity KeycloakService { static auth: whatever = {}; static init(): Promise<any> { allow keycloakAuth: whatever = novel Keycloak('assets/keycloak.json'); KeycloakService.auth.loggedIn = false; render novel Promise((resolve, reject) => { keycloakAuth.init({ onLoad: 'check-sso' }) .success(() => { KeycloakService.auth.loggedIn = true; KeycloakService.auth.authz = keycloakAuth; KeycloakService.auth.logoutUrl = keycloakAuth.authServerUrl + "/realms/" + environment.keycloakRealm + "/protocol/openid-connect/logout?redirect_uri=http://localhost:4200/index.html"; resolve(); }) .error(() => { reject(); }); }); } // to a greater extent than methods hither }
This service loads keycloak.json from assets folder. It initialize keycloak using 'check-sso' parameter. Why? So that angular volition non redirect to keycloak's login page every fourth dimension nosotros access a page. If login is successful nosotros shop the keycloak object inwards keyClockService's auth variable. Note that this variable is static, thus nosotros tin access it inwards whatever of our angular's components, equally long equally nosotros inject the service. - Since nosotros used check-sso parameter inwards keycloak, nosotros involve to manually secure the routes, which nosotros don't desire to move accessible yesteryear the full general public. To practice that, nosotros involve to practice a guard that nosotros tin role inwards Routes. This is how nosotros define the guard:
import { Injectable } from '@angular/core'; import { Router, CanActivate, CanLoad } from '@angular/router'; import { Logger } from "angular2-logger/core"; import { KeycloakService } from 'app/core/auth/keycloak.service'; @Injectable() export course of educational activity AuthGuardService implements CanActivate, CanLoad { constructor(public router: Router, soul keycloakService: KeycloakService, soul logger: Logger) { } canActivate(): boolean { render false; } canLoad(): boolean { if (KeycloakService.auth.loggedIn && KeycloakService.auth.authz.authenticated) { this.logger.info("user has been successfully authenticated"); render true; } else { KeycloakService.login(); render false; } } }
- Now nosotros involve to declare our AuthGuardService inwards our providers, thus the organisation tin access it. Open your app.module.ts too add together it:
AuthGuardService, { provide: HTTP_INTERCEPTORS, useClass: SecuredHttpInterceptor, multi: truthful },
- Then inwards our Routes Definition (I assume y'all bring app-routing.module.ts) nosotros guard the Routes similar this:
{ path: 'dashboard/vendor', canLoad: [AuthGuard], loadChildren: 'app/module/dashboard/vendor/vendor.module#VendorModule' }
- At this signal all our prerequisites to secure the angular app had been already fulfilled. We merely involve to initialize keycloak somewhere when nosotros access the app too at that topographic point is no improve house to practice that but inwards main.ts.
KeycloakService.init() .then(() => { const platform = platformBrowserDynamic(); platform.bootstrapModule(AppModule); }) .catch(() => window.location.reload());
Perfect. Now keycloak volition practice aught if at that topographic point is no session cookie. Otherwise, it volition login automatically too if the session is valid, redirects dorsum to the app. - Since around angular apps access a REST API, nosotros commonly would desire to add together a bearer token on whatever asking whenever nosotros bring an authenticated user. We practice that yesteryear implementing the newly introduced HttpInterceptor. And this is how nosotros practice it:
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/do'; import { KeycloakService } from 'app/core/auth/keycloak.service'; @Injectable() export course of educational activity SecuredHttpInterceptor implements HttpInterceptor { intercept( request: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> { KeycloakService.getToken(); allow kcToken = KeycloakService.auth.authz.token; if (KeycloakService.auth.loggedIn && KeycloakService.auth.authz.authenticated) { asking = request.clone({ setHeaders: { Authorization: 'Bearer ' + kcToken } }); } render next.handle(request); } }
- Finally nosotros bring everything to secure our angular app.
Demo template is available for sale for $50. You tin ship payment via skype at: czetsuya@gmail.com
0 komentar:
Please comment if there are any that need to be asked.