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.
Let’s start off by getting all the variable declarations etc. out of the way.
export class AppComponent {
titleToken = 'User Information Obtained from the Token';
titleAPIList = 'User List obtained via Keycloak HTTP API call';
isTokenCardVisible: boolean = false;
isAPICardsVisible: boolean = false;
username: string;
fullName: string;
usersArray = [];
constructor(private keycloakHttp: KeycloakHttp) {
}
reset(): void {
this.isTokenCardVisible = false;
this.isAPICardsVisible = false;
this.usersArray = [];
}
}
In the code block above you can see that I’ve declared quite a few variables that’ll be used throughout this part.
titleToken – This is the variable which contains the get user information from the token section’s title.
titleAPIList – This is the variable which contains the get a list of users from an API call section’s title.
isTokenCardVisible – This is a variable which controls the visibility for the Token section.
isAPICardsVisible – This is a variable which controls the visibility for the API call section.
username – This will be the reference variable for the username obtained from the Token.
fullName – This will be the reference variable for the full name obtained from the Token.
usersArray – This will be the reference array for the list of users obtained from the API call.
constructor – We need to initialize a new instance variable for the KeycloakHttp class so we can use it in our API call.
reset – This method will reset and clear the variables to their default state.
Create a locally stored JSON Flat File of Users
Create a new package called api in the src/app root, then create a new users.json file and insert a few dummy users, as can be seen in the code block below.
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).
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.
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…
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.
If you have any ideas, requests or questions for implementing any Angular 2+ features (in the context of this blog series), feel free to share it with us in the comment section below.
If you haven’t read the previous parts of this series:
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
andKeycloak.service.ts
classes, as well as various other classes. In this part we’ll log into the application viaKeycloak
, get certain parameters from theauthenticated token
via theKeycloak Service
, and finally I’ll show an example HTTP call via theKeycloakHTTP
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.
https://drive.google.com/open?id=0B4H8V7DA5DrJMnpJZTF3YTRsOGM
Base Code in AppComponent 1
Let’s start off by getting all the variable declarations etc. out of the way.
In the code block above you can see that I’ve declared quite a few variables that’ll be used throughout this part.
titleToken
– This is the variable which contains the get user information from the token section’s title.titleAPIList
– This is the variable which contains the get a list of users from an API call section’s title.isTokenCardVisible
– This is a variable which controls the visibility for the Token section.isAPICardsVisible
– This is a variable which controls the visibility for the API call section.username
– This will be the reference variable for the username obtained from theToken
.fullName
– This will be the reference variable for the full name obtained from theToken
.usersArray
– This will be the reference array for the list of users obtained from theAPI call
.constructor
– We need to initialize a new instance variable for theKeycloakHttp
class so we can use it in ourAPI call
.reset
– This method will reset and clear the variables to their default state.Create a locally stored JSON Flat File of Users
Create a new package called
api
in thesrc/app
root, then create a newusers.json
file and insert a few dummy users, as can be seen in the code block below.Navigate to and open the
.angular-cli.json
file in the project root; update theassets
section to reflect the code below (we need to add this in order for thewebpack
compiler to include it in a production build).Navigate to and open both your
environment.ts
andenvironment.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 tohttp://localhost:4200
(unless you’ve specified another port on which the application must be served). Make sure that yourKeycloak
server is up and running. At this point you should be redirected to theKeycloak realm
authentication screen. This happens because theKeycloak 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 tohttp://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-topBootstrap 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 aKeycloakHTTP 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 thegetUserInfoFromToken()
, thegetUsersFromJsonApi()
andlogout()
click event method declarations; the logic will be handled in theComponent’s code
.AppComponent TypeScript Code 2
In the code block above notice the line of code in the
logout()
method; I invoke thelogout
method from theKeycloakService
class statically. If you want to do it differently you can remove thestatic
keyword from thelogout
method in theKeycloakService
class and create a new private instance variable in theAppComponent
constructor. The code block below shows the difference (excluding theKeycloakService
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 theLogout
button the system should invalidate your current session token and log you out, and finally redirect to you back to theKeycloak Realm login
page.Get User Information from Token
On a
Keycloak Client
you can specify custom tokenmappers
, some of the default mappers include: full name (User’s full name), username (User’s username), email (User’s email address). Let’s write theHTML
code to display the current logged in user’s full name and username on aBootstrap 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 thecontainer
is the content section which is triggered when the user clicks on theAngular Keycloak Blog Series – Part 6
item in the menu; in theHTML
code snippet number 1 you can see that when the user clicks on that specific link thereset()
method is called in theAppComponent
. The seconddiv
inside thecontainer
contains the code associated with theToken
trigger.The
*ngIf=”isTokenCardVisible”
clause is the toggle function for the visibility of thediv content section
. The title, username, and full name values are all set by making use ofInterpolated 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 returnedJSON array of users
.AppComponent HTML Code 3
Add the following code below the
Token div
(it should be the thirddiv
inside thecontainer
).{{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 thediv content section
. The title value is set by making use ofInterpolated Data Binding
. We make use of acard-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 theusersArray
a new card should be created.AppComponent TypeScript Code 4
Make use of the
keycloakHttp
instance variable declared and instantiated in theconstructor
method of theAppComponent
to initialize a newHTTP GET
request. Next specify the endpoint for theusers.json
flat file created at the beginning of this blog entry. Next we need tomap
the response of theHTTP GET
method tojson()
.We’re making use of
Observables
; thus we need to subscribe to theHTTP GET
method in order to tell theAngular eco-system
that it should execute the method and in turn make theHTTP GET
call. If you don’tsubscribe
to themethod
it won’t be executed. Once we’vesubscribed
to the method it will execute and in turn we can then map the returned dataresult
to ourusersArray
variable. Next we set theisAPICardsVisible
variable totrue
so that we can trigger the visibility of the content section on theComponent’s view
.Browser Network Request
Once you click on the
Get User List from API
link in the menu bar theKeycloakHttp
method will be called, as can be seen in the code block below therequest headers
has been automagically updated to include theAuthorization
token with the value ofBearer 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.Keycloak server
and the configuration thereof (including realms, clients, and users).Angular
development environment and the setting up of a new project as well as the configuration thereof (including the installation of dependencies such asBootstrap, jQuery, PopperJs and KeycloakJs
).Angular
concepts throughout the series.Angular
environment/project to be able to make use ofKeycloak
. Although there’s still a lot of scope for expanding the series with more parts (as we all know by nowKeycloak
has a ton of features we could still implement); I feel that at this stage the objective has been met.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.
If you have any ideas, requests or questions for implementing any Angular 2+ features (in the context of this blog series), feel free to share it with us in the comment section below.