Integrating Keycloak with an Angular 4 Web Application – Part 6

Background – Angular – Keycloak blog series Part 6

Welcome to part six of the blog series called “Integrating Keycloak with an Angular 4 web application”. Before we continue where we left off in part five of the series, let’s do a quick recap of part five as well as what we’ll cover in this part.

In part five, we implemented code for both the Keycloak.http.ts and Keycloak.service.ts classes, as well as various other classes. In this part we’ll log into the application via Keycloak, get certain parameters from the authenticated token via the Keycloak Service, and finally I’ll show an example HTTP call via the KeycloakHTTP class.

Project Code Link

If you want to download the project to reference the code base you can do so simply by navigating to the following link and downloading the project.

Navigate to and open the .angular-cli.json file in the project root; update the assets section to reflect the code below (we need to add this in order for the webpack compiler to include it in a production build).

"assets": [
"assets",
"favicon.ico",
"./app/api/users.json"
],

Navigate to and open both your environment.ts and environment.prod.ts files and add a new endpoint, as can be seen in the code block below.

Sign in Via Keycloak

Now that we’ve got that out of the way we can continue where we left off in part five, we can test our code changes by compiling and serving the project via the ng serve command. Once the process has been completed, open up your favorite web browser and navigate to http://localhost:4200 (unless you’ve specified another port on which the application must be served). Make sure that your Keycloak server is up and running. At this point you should be redirected to the Keycloak realm authentication screen. This happens because the Keycloak Service picked up that you don’t have a valid authentication token. In part two, we created a user for the realm.

You need to make use of that user’s information (i.e. username and password) to log into the application. Enter the username and password and click on the Login button. Keycloak should authenticate the user and redirect back to http://localhost:4200 and you should see the home page of the application.

Sign Out Via Keycloak

The next logical step is for users to be able to log out of the application. This will require us to write a few lines of code. Open up your app.component.html file (which can be found in the root of the project; src/app).

AppComponent HTML Code 1

The HTML code in the code block above should look familiar to you if you’ve ever used bootstrap, if it doesn’t then don’t worry, all I’ve done is to create a sticky-top Bootstrap 4 navbar with a link to get the user information from the token, a link to get a list of users by making use of a KeycloakHTTP API call and a button to the right hand side of the screen where users will be able to log out. The important thing is that you recognize the getUserInfoFromToken(), the getUsersFromJsonApi() and logout() click event method declarations; the logic will be handled in the Component’s code.

AppComponent TypeScript Code 2

logout(): void {
KeycloakService.logout();
}

In the code block above notice the line of code in the logout() method; I invoke the logout method from the KeycloakService class statically. If you want to do it differently you can remove the static keyword from the logout method in the KeycloakService class and create a new private instance variable in the AppComponent constructor. The code block below shows the difference (excluding the KeycloakService class change).

If you take a look at your browser window you should see the relevant HTML code display a dark navbar with a few items on it. If you click on the Logout button the system should invalidate your current session token and log you out, and finally redirect to you back to the Keycloak Realm login page.

Get User Information from Token

On a Keycloak Client you can specify custom token mappers, some of the default mappers include: full name (User’s full name), username (User’s username), email (User’s email address). Let’s write the HTML code to display the current logged in user’s full name and username on a Bootstrap 4 card.

AppComponent HTML Code 2

Click on the menu items

{{titleToken}}

Logged In User Information

Username – {{username}}

Full Name – {{fullName}}

The first div inside the container is the content section which is triggered when the user clicks on the Angular Keycloak Blog Series – Part 6 item in the menu; in the HTML code snippet number 1 you can see that when the user clicks on that specific link the reset() method is called in the AppComponent. The second div inside the container contains the code associated with the Token trigger.

The *ngIf=”isTokenCardVisible” clause is the toggle function for the visibility of the div content section. The title, username, and full name values are all set by making use of Interpolated Data Binding.

AppComponent TypeScript Code 3

We set the `username` and the `fullName` variable values by invoking their relevant method from the `KeycloakService`. Finally set the `isTokenCardVisible` variable’s value to `true` so that the card can be shown in the component’s view (as per the `ngIf` clause).

Making use of KeycloakHTTP to make API Calls

Rather than setting up an entire backend service to handle requests and return data, I’ve created a JSON flat-file which will serve as the list of users we want to return. We’ll use the location of this file as our ‘API-endpoint’. It will mimic the returned JSON array of users.

AppComponent HTML Code 3

Add the following code below the Token div (it should be the third div inside the container).

{{titleAPIList}}

User Information Card {{userItem.id}}

Username – {{userItem.username}}

Full Name – {{userItem.fullName}}

The *ngIf=”isAPICardsVisible” clause is the toggle function for the visibility of the div content section. The title value is set by making use of Interpolated Data Binding. We make use of a card-deck div to display all the separate cards in the list next to each other (horizontally). The *ngFor=”let userItem of usersArray” clause is where we iterate through the array. In a nutshell for every item in the usersArray a new card should be created.

Make use of the keycloakHttp instance variable declared and instantiated in the constructor method of the AppComponent to initialize a new HTTP GET request. Next specify the endpoint for the users.json flat file created at the beginning of this blog entry. Next we need to map the response of the HTTP GET method to json().

We’re making use of Observables; thus we need to subscribe to the HTTP GET method in order to tell the Angular eco-system that it should execute the method and in turn make the HTTP GET call. If you don’t subscribe to the method it won’t be executed. Once we’ve subscribed to the method it will execute and in turn we can then map the returned data result to our usersArray variable. Next we set the isAPICardsVisible variable to true so that we can trigger the visibility of the content section on the Component’s view.

Browser Network Request

Once you click on the Get User List from API link in the menu bar the KeycloakHttp method will be called, as can be seen in the code block below the request headers has been automagically updated to include the Authorization token with the value of Bearer eyJhbG…

Closing thoughts for Part 6 (And The Series)

With that the Integrating Keycloak with and Angular 4 Web Application blog series comes to an end. If you’ve followed the series from part one right through until now, I would like to thank you for your patience. I hope you had as much fun as I did throughout the set-up and writing of this blog series. Let’s take a look at some of the major things we’ve covered.

Installing and configuring a Keycloak server and the configuration thereof (including realms, clients, and users).

Installing and configuring an Angular development environment and the setting up of a new project as well as the configuration thereof (including the installation of dependencies such as Bootstrap, jQuery, PopperJs and KeycloakJs).

We’ve discussed some core Angular concepts throughout the series.

At the end of this part you should be able to configure your Angular environment/project to be able to make use of Keycloak. Although there’s still a lot of scope for expanding the series with more parts (as we all know by now Keycloak has a ton of features we could still implement); I feel that at this stage the objective has been met.

Having said that, it doesn’t mean that possible future parts are out of the question forever.

If you want more information on Keycloak, Angular, Bootstrap or Node JS you can visit the links below to read up, practice and improve your skillset.

Hello, thank you very much for your articles. I was wondering if it is possible to explain how to do the login/logout without using the keycloak pages, I mean using an angular pages integrated in our app. I know that we can use the SSO, can you please suggest any technique ? thank you

This issue got resolved when I strike off code from main.ts that reload the window the problem got resolved but now struggling with new issue of No “Access-Control-Allow-Origin” while running keycloak and angular web app on localhost on Chrome. Will update once that works.

Hello, thank you for the series. I am implementing this for my company and it is really helpful. I have a question. Your method secures the angular app by integrating with the keycloak server. In addition to the web application I have a node server with endpoints for data retrieval. How can this endpoint be secured with keycloak. I have gone down the route of using keycloak-nodejs-connect. I can login and logout using redirection strategy but token refresh is a problem for my single page application. Do you have any thoughts on how teh server and the SPA web application can both be seamlessly integrated with keycloak.

Thanks for your comment, and reading the series. Unfortunately I cannot comment on any NodeJS (backend) related integration with Keycloak as I haven’t played around with it as of yet. Hope you get it sorted 🙂

Hello Walter,
Just a follow-up note to say I found the solution to refreshing the token asynchronously with keycloak-connect. Keycloak-connect as the nodjs adapter for keycloak has a method in the GrantManager class that can be used to refresh the JWT token. The code below does the job.

The ‘ensureFreshness’ method takes two parameters. The first is the grant (obtained after a successful login). The second is a callback that can be used to execute any business logic after the the token is refreshed.

The other techniques I had to implement was to override the redirect method in Nodejs so that instead of sending a 302 ‘redirect’ respose to the browser, I attach a header and send a 401 response. The redirect response is used by keycloak-connect in situations such as when the login session has expired. Unfortunately redirects and ajax calls dont fit well together.

I was wondering if it is possible to explain how to do the login/logout without using the keycloak pages, I am planning on using Angularjs 4 to call API for Authentication(Spring keycloack adapter) and Keycloak server

Hi Nicholus,
It should be possible yes, your authentication flow will be different than what is described in this tutorial series.
You could implement a solution where you call the keycloak service (when the user clicks on a login button for example, where they provide the username, password combination) in order to obtain a valid access token, then make use of the access token to authenticate via some (probably your own custom) REST API, and handle the logic from there. I didn’t include any backend related code for this tutorial series on purpose as it’s outside the scope of the project.

In your Keycloak server naviagte to your realm and then to the client you have created. Right at the bottom of the client settings page you’ll get Web Origins where you can specify the CORS origins. You can add * (asterisk) to allow all origins.