Halem  Rostt

Halem Rostt


How to Add KeyCloak in Angular for SSO Authentication


Security is one of the central components of developing web applications. Single sign-on is the authentication mechanism that permits users to access different or multiple applications with one set of credentials or by logging in once. Basically, It minimizes the management of various users and passwords.

This is how SSO works with keycloak. Users authenticate with Keycloak rather than individual applications. This means that your applications don’t have to deal with login forms, authenticating users, and storing users. Once logged-in to Keycloak, users don’t have to login again to access a different application.

This also applied to logout. Keycloak provides single-sign out, which means users only have to logout once to be logged out of all applications that use Keycloak.

In this post. we will see how to integrate keycloak with the Angular app for the SSO.

Example Project

SSO lets you access multiple applications by only logging in once so we are going to run two applications to see how it works. Here are the two example projects for you to run on your local machine.

// todos
git clone https://github.com/bbachi/keycloak-todos.git
npm install
npm start

// tasks
git clone https://github.com/bbachi/keycloak-tasks.git
npm install
npm start

Here is an example of Keycloak in action. Make sure the Keycloak server is running on port 8080. Start your Angular project and load it in the browser. If the user is not logged in, he will be redirected to the Keycloak login page. Once you log in you can refresh the app or directly access the application without logging in again until you log out.

Running keyCloak server on Local

We need a keycloak server for authentication to access applications. You need to run the Keycloak server on your machine. Let’s do that.


You need to download the keycloak from this page. Download the server zip.

Running on Local machine

Extract the zip into whatever the folder you want. Change the directory into keycloak-8.0.0/bin and run this file ./standalone.sh

Once the startup is done, you can access the admin console on this address http://localhost:8080/auth/

When you access for the first time you need to create an admin user to manage all the aspects of the keycloak server.

Once created, you can log in with the newly created username and password. You will be redirected to the default realm which is master. You can create your own realms and as many as you want.

Creating Realms, Users, Roles, and clients

We are running a keycloak server on our local machine. It’s time to create some configuration now. This is very basic and we are creating what we need for this project and get familiar with the keycloak.

Realms: A Realm can group users, roles, and clients and is completely isolated from one another. We have two applications todos and tasks we can create one realm for these apps if you want to maintain under one.

Users: These are the normal users who can log in to the applications. You can create users under the realm or you can create groups and add the users to the group.

Roles: Roles can be assigned to the users so that we can have granular control over the applications. For example, if the admin role is created and assigned to the user. the user can access full access to the application.

Clients: Clients are the applications themselves. We have two applications todos and tasks for this post. We need to create these as clients with some id, baseurl, etc.

How To Integrate Angular With KeyCloak

First, we need to install the library angular-oauth2-oidc for integration with keycloak.

npm install angular-oauth2-oidc --save

Create a service that takes care of getting access token from the Keycloak server. This is how it works, the OAuthService has method loadDiscoveryDocumentAndLogin() which returns promise if the user is already logged in and if not, it will redirect to the login page by calling this method initImplicitFlow() and returns reject function.

import { Injectable } from '@angular/core';
import { AuthConfig, NullValidationHandler, OAuthService } from 'angular-oauth2-oidc';
import { filter } from 'rxjs/operators';

export class AuthConfigService {
    private _decodedAccessToken: any;
    private _decodedIDToken: any;
    get decodedAccessToken() { return this._decodedAccessToken; }
    get decodedIDToken() { return this._decodedIDToken; }

      private readonly oauthService: OAuthService,
      private readonly authConfig: AuthConfig
    ) {}

    async initAuth(): Promise<any> {
      return new Promise((resolveFn, rejectFn) => {
        // setup oauthService
        this.oauthService.tokenValidationHandler = new NullValidationHandler();
        // subscribe to token events
          .pipe(filter((e: any) => {
            return e.type === 'token_received';
          .subscribe(() => this.handleNewToken());
        // continue initializing app or redirect to login-page
        this.oauthService.loadDiscoveryDocumentAndLogin().then(isLoggedIn => {
          if (isLoggedIn) {
          } else {
    private handleNewToken() {
      this._decodedAccessToken = this.oauthService.getAccessToken();
      this._decodedIDToken = this.oauthService.getIdToken();



This service needs a configuration such as redirect_url, client_id, issuer, etc. The issuer is responsible for authentication and providing access token, client_id is the client name registered in the Keycloak server and the redirect Url is the URL that should be redirected to after successful authentication. The configuration is taken from these files.

import { AuthConfig } from 'angular-oauth2-oidc';
import { environment } from '../environments/environment';

export const authConfig: AuthConfig = {

    // Url of the Identity Provider
    issuer: environment.keycloak.issuer,

    // URL of the SPA to redirect the user to after login
    redirectUri: environment.keycloak.redirectUri,

    // The SPA's id. 
    // The SPA is registerd with this id at the auth-serverß
    clientId: environment.keycloak.clientId,

    responseType: environment.keycloak.responseType,
    // set the scope for the permissions the client should request
    // The first three are defined by OIDC.
    scope: environment.keycloak.scope,
    // Remove the requirement of using Https to simplify the demo
    requireHttps: environment.keycloak.requireHttps,
    // at_hash is not present in JWT token
    showDebugInformation: environment.keycloak.showDebugInformation,
    disableAtHashCheck: environment.keycloak.disableAtHashCheck

export class OAuthModuleConfig {
    resourceServer: OAuthResourceServerConfig = {sendAccessToken: false};

export class OAuthResourceServerConfig {
     * Urls for which calls should be intercepted.
     * If there is an ResourceServerErrorHandler registered, it is used for them.
     * If sendAccessToken is set to true, the access_token is send to them too.
    allowedUrls?: Array<string>;
    sendAccessToken = true;
    customUrlValidation?: (url: string) => boolean;


// The file contents for the current environment will overwrite these during build.
// The build system defaults to the dev environment which uses `environment.ts`, but if you do
// `ng build --env=prod` then `environment.prod.ts` will be used instead.
// The list of which env maps to which file can be found in `.angular-cli.json`.

export const environment = {
  production: false,
  envName: 'local',
  keycloak: {
    // Url of the Identity Provider
    issuer: 'http://localhost:8080/auth/realms/tasks',

    // URL of the SPA to redirect the user to after login
    redirectUri: 'http://localhost:4200/',

    // The SPA's id. 
    // The SPA is registerd with this id at the auth-serverß
    clientId: 'todo-ui',

    responseType: 'code',
    // set the scope for the permissions the client should request
    // The first three are defined by OIDC.
    scope: 'openid profile email',
    // Remove the requirement of using Https to simplify the demo
    requireHttps: false,
    // at_hash is not present in JWT token
    showDebugInformation: true,
    disableAtHashCheck: true


Notice the issuer and redirectUrl in the above file and make sure your keycloak server is running at the same time.

Create a separate Module so that you can import all this into AppModule. We have to use APP_INITIALIZER so that we can authenticate the user before bootstrapping the app.

import { NgModule, APP_INITIALIZER } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { OAuthModule, AuthConfig } from 'angular-oauth2-oidc';

import { AuthConfigService } from './authconfig.service';
import { authConfig, OAuthModuleConfig } from './auth.config';

export function init_app(authConfigService: AuthConfigService) {
    return () => authConfigService.initAuth();

  imports: [ HttpClientModule, OAuthModule.forRoot() ],
  providers: [
    { provide: AuthConfig, useValue: authConfig },
      provide: APP_INITIALIZER, 
      useFactory: init_app, 
      deps: [ AuthConfigService ], 
      multi: true
export class AuthConfigModule { }


You need to have a logout functionality as well and that’s usually implemented in the header.

<div class="header">
    <div class="row">
        <div class="col-md-9">
            <h1 style="text-align: center;">Tasks</h1>
        <div class="col-md-3">
            <h4><a href="#" (click)="logout()">Logout</a></h4>
import { Component, OnInit } from '@angular/core';
import { OAuthService } from 'angular-oauth2-oidc';

  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
export class HeaderComponent implements OnInit {

  constructor(private readonly oauthService: OAuthService) { }

  ngOnInit() {

  logout() {


logout functionality in the Header

Finally, we need to import this module in the AppModule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AuthConfigModule } from '../config/auth.config.module';
import { HeaderComponent } from './header/header.component';

  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }


Running Multiple Apps With SSO

We have seen the integration code and basic stuff about the Keycloak server on how to create clients, roles and users. Let’s run two apps together.

I have created two clients in the Keycloak server which runs on ports 4200 and 4201 respectively.


You should have valid redirectUrl to be http://localhost:4200 and http://localhost:4201 as well.

tasks-ui client

todo-ui client

You need to create a role called admin under each client.

Add role under each client

Then you need to create a user bachi1(you can create whatever the name you want) and add that user to the role admin

User Creation

assign the user to admin role under role mappings

Once done, clone these two projects run on your local machine on ports 4200 and 4201 respectively.

// todos runs on 4201
git clone https://github.com/bbachi/keycloak-todos.git
npm install
npm start

// tasks runs on port 4200
git clone https://github.com/bbachi/keycloak-tasks.git
npm install
npm start

Here is the small demonstration if you log into one app and you can actually login to another one without providing any credentials until you log out.

Keycloak in action


  • Keycloak makes it easier to secure your applications with little to no code. It provides a lot of features such as Single sign-on, single sign out, Kerberos bridge, Identity Brokering, and Social Login, User Federation, etc.
  • Users authenticate with Keycloak rather than individual applications. This means that your applications don’t have to deal with login forms.
  • SSO lets you access multiple applications by only logging in once. We testes two application in this post.
  • We can run the Keycloak server on your local machine by running ./standalone.sh under bin folder of keycloak.
  • There are Realms, Users, Roles, and clients we can define in the keycloak.
  • Realms can group users, clients, and roles. Clients are the applications themselves.
  • We need to use this library angular-oauth2-oidc for the keycloak integration with Angular.
  • Make sure you run the Keycloak server along with your application to test keycloak on your local machine.
  • We need to use APP_INITIALIZER to check the authentication before bootstrapping the main app.


Keycloak makes it easier to implement SSO from small scale organizations to big organizations. Keycloak provides you a lot of features with little or no code.

Thank you for reading!

#javascript #angular #development #programming #webdev

What is GEEK

Buddha Community

How to Add KeyCloak in Angular for SSO Authentication

How To Set Up Two-Factor Authentication in cPanel

What is 2FA
Two-Factor Authentication (or 2FA as it often referred to) is an extra layer of security that is used to provide users an additional level of protection when securing access to an account.
Employing a 2FA mechanism is a vast improvement in security over the Singe-Factor Authentication method of simply employing a username and password. Using this method, accounts that have 2FA enabled, require the user to enter a one-time passcode that is generated by an external application. The 2FA passcode (usually a six-digit number) is required to be input into the passcode field before access is granted. The 2FA input is usually required directly after the username and password are entered by the client.

#tutorials #2fa #access #account security #authentication #authentication method #authentication token #cli #command line #cpanel #feature manager #google authenticator #one time password #otp #otp authentication #passcode #password #passwords #qr code #security #security code #security policy #security practices #single factor authentication #time-based one-time password #totp #two factor authentication #whm

Christa  Stehr

Christa Stehr


Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

Angular 12 + Spring Boot: JWT Authentication example | Spring Security

In this tutorial, I will show you how to build a full stack Angular 12 + Spring Boot JWT Authentication example. The back-end server uses Spring Boot with Spring Security for JWT Authentication & Role based Authorization, Spring Data JPA for interacting with database. The front-end will be built using Angular 12 with HttpInterceptor & Form validation.

Related Posts:

– Angular 12 + Spring Boot: CRUD example

– Angular 12 + Spring Boot: File upload example

– Spring Boot, MongoDB: JWT Authentication with Spring Security

Contents [hide]

#angular #full stack #spring #angular #angular 12 #authentication #authorization #jwt #login #registration #security #spring boot #spring security #token based authentication

Roberta  Ward

Roberta Ward


Basics of Angular: Part-1

What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular.

Angular is a Typescript-based open-source front-end web application platform. The Angular Team at Google and a community of individuals and corporations lead it. Angular lets you extend HTML’s syntax to express your apps’ components clearly. The angular resolves challenges while developing a single page and cross-platform applications. So, here the meaning of the single-page applications in angular is that the index.html file serves the app. And, the index.html file links other files to it.

We build angular applications with basic concepts which are NgModules. It provides a compilation context for components. At the beginning of an angular project, the command-line interface provides a built-in component which is the root component. But, NgModule can add a number of additional components. These can be created through a template or loaded from a router. This is what a compilation context about.

What is a Component in Angular?

Components are key features in Angular. It controls a patch of the screen called a view. A couple of components that we create on our own helps to build a whole application. In the end, the root component or the app component holds our entire application. The component has its business logic that it does to support the view inside the class. The class interacts with the view through an API of properties and methods. All the components added by us in the application are not linked to the index.html. But, they link to the app.component.html through the selectors. A component can be a component and not only a typescript class by adding a decorator @Component. Then, for further access, a class can import it. The decorator contains some metadata like selector, template, and style. Here’s an example of how a component decorator looks like:

    selector: 'app-root',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.scss']

Role of App Module

Modules are the package of functionalities of our app. It gives Angular the information about which features does my app has and what feature it uses. It is an empty Typescript class, but we transform it by adding a decorator @NgModule. So, we have four properties that we set up on the object pass to @NgModule. The four properties are declarations, imports, providers, and bootstrap. All the built-in new components add up to the declarations array in @NgModule.

declarations: [
imports: [
bootstrap: [AppComponent]

What is Data Binding?

Data Binding is the communication between the Typescript code of the component and the template. So, we have different kinds of data binding given below:

  • When there is a requirement to output data from our Typescript code in the HTML template. String interpolation handles this purpose like {{data}} in HTML file. Property Binding is also used for this purpose like [property] = “data”.
  • When we want to trigger any event like clicking a button. Event Binding works while we react to user events like (event) = “expression”.
  • When we can react to user events and output something at the same time. Two-way Binding is used like [(ngModel)] = “data”.

image for understanding data binding

#angular #javascript #tech blogs #user interface (ui) #angular #angular fundamentals #angular tutorial #basics of angular

Ayyaz Zafar


Angular Material Autocomplete - Multiple Use Cases covered

Learn How to use Angular Material Autocomplete Suggestions Search Input. I covered multiple use cases.

Please watch this video. I hope this video would be helpful for you to understand it and use it in your projects

Please subscribe: https://www.youtube.com/channel/UCL5nKCmpReJZZMe9_bYR89w

#angular #angular-material #angular-js #autocomplete #angular-material-autocomplete #angular-tutorial