Keycloak Integration : Part 2: Integration with Angular Frontend

Logo courtesy and

Keycloak is an Open Source Identity and Access Management For Modern Applications and Services.

In this series, other articles

Acceptance Criteria

  • From angular, when user is not logged In, user should be taken to Keycloak Login page.
  • After login, user should be taken back to angular app
  • From access token, angular app should be able to know user roles, controls routes which are accessible based on roles
  • Angular app should be able to get user attributes (dynamic key value pairs) that are associated with the User.

Pre-requisites (Keycloak side)

Pre-requisites (angular side)

  • Add npm dependency — keycloak-angular.
  • To src/environments/environment.ts make equivalent changes, like below
sample environment.ts

User log in flow

  • We could use a CanActivate angular directive to control access to specific paths based on user roles
  • KeycloakAuthGuard provides a base implementation of it, which is available from keycloak-angular dependency
  • Let’s extend KeycloakAuthGuard
  • Let’s update our angular routing module, like this
  • After the above changes, if we try to visit the paths that has CanActivate and if the user is not logged in, user will be taken to login page. This happens because of Valid Redirect URL and WebOrigin that we configured in the client settings in Keycloak

Fetching User Attributes and Group Attributes

User Attributes are very useful to handle dynamic key value pairs associated for each user. Groups can also have attributes. Any user who belongs to the Group inherits those attributes.

There are many ways to fetch user attributes. I personally prefer, it they stay in token, so applications can decode the JWT token and get the attributes.

To do this, we need a Protocol Mapper — that can map keycloak information into a OpenId Connect token. The documentation doesn’t have a good example of User Attribute mapping. Here is a good example

To read the token at the angular side, here is a code sample:

Debugging Tokens details issued by Keycloak

There are times, when we need to dive deep and understand the content of the token. This happens when we configure user in Keycloak expected something but actual behavior is different (like Authorization flow)

Good read : 5-easy-steps-to-understanding-json-web-tokens-jwt
Chrome developer tools > Network Tab

Copy the access token, and paste into

A section from unpacked Token

Since JWT tokens are just base64urlencoded string, it will unpack the content and show the roles and other details that the token payload has.