Keycloak Integration in Angular Application

anjnkmr

Anjan Kumar

Posted on June 25, 2020

Keycloak Integration in Angular Application

What is Keycloak?

  • An Open Source Identity and Access Management for Modern Applications and Services.
  • One of the opensource implementation of OpenID protocol.
  • Simple Identity Layer on top of OAuth2.0 protocol

Why do we need Keycloak in Angular?

  • To secure our application from unauthorized access
  • To identify who is the user of the application, to show the relevant content & authorized content.

Prerequisites

  1. Angular 6/+ Application

Steps to Integrate Keycloak in Angular Application

  1. Install Keycloak JS package
    1. npm i --save keycloak-js
  2. Install Keycloak Angular package
    1. npm i --save keycloak-angular
  3. Keycloak Server Configuration
    1. environment.ts
  4. Keycloak Initialization
    1. Create a file AppInit.ts in the project src directory AppInit.ts
  5. Integrating into AppModule (Refer the image below these points)

    1. Import KeycloakAngularModule in AppModule
    2. Register Provider KeyloackService
    3. Register Provider of type APP_INITIALIZER with initializer we defined in AppInit.ts
    4. Register Provider AuthService (You can find the AuthService implementation below)

    AuthService
    auth.service.ts
    AppModule
    app-module.ts

  6. Guard configuration

    1. Create a Guard ng new g auth
    2. Change the definition of the class as below, notice the extends auth.guard.ts
    3. Routing Module Configuration, Use the AuthGuard for routes that you want to restrict access, Assign required roles for each route in data attribute, roles parameter as an array. app-routing.module.ts
  7. Start the application ng s, then you will have the login screen provided by the Keycloak, log in with the correct user to access your application who has the roles that are assigned in the routing configuration

    Keycloak Login Screen

💖 💪 🙅 🚩
anjnkmr
Anjan Kumar

Posted on June 25, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related