AmitK
AmitK

Reputation: 81

How to connect and configure angular app to get authenticated by Keycloak

I have setup keycloak server with all required configuration done like realm, client, users, roles etc. Now I have on angular application which is acting as frontend. Need to integrate this app with keycloak to provide authentication.

Angular app should redirect to Keycloak, Keycloak should do the user validation , Keycloak should provide access token after successful validation and finally angular app should be able to access spring boot API's with token provided by keycloak. Typical OAuth2.0 Flow. I am new to angular, so can anyone provide sample application code (github) for angular-keycloak integration. Also keycloak adapter for angular is required.

Keycloak version - 4.0.0.Final
Angular version - 1 but to be upgraded to 6

I am getting following error while downloading keycloak adapter for angular-

>npm install [email protected]
npm ERR! code ECONNRESET
npm ERR! errno ECONNRESET
npm ERR! network request to https://registry.npmjs.org/keycloak-angular failed, reason: read ECONNRESET
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\40005928\AppData\Roaming\npm-cache\_logs\2019-07-11T11_42_38_802Z-debug.log.

Upvotes: 1

Views: 2709

Answers (1)

Abhijit Gorde
Abhijit Gorde

Reputation: 31

Angular web application should be higher than 4.3 to integrate Keycloak.

Follow below steps to configure Keycloak: 1. Install Keycloak npm package

npm i keycloak-angular 2. Create app-init.ts file and add below contain:

import { KeycloakService } from 'keycloak-angular';
declare var keycloak : KeycloakService;
export function initializer(keycloak: KeycloakService): () => Promise<any> {   
  return (): Promise<any> => keycloak.init(
  {
    config: {
        url: 'keycloak_URL',
        realm: ''keycloak_ralm_name'',
        clientId: 'keycloak_client_name'
    },
    initOptions: {
      onLoad: 'login-required',
      checkLoginIframe: false
    },
    enableBearerInterceptor: false
  });}
  1. Modify AppComponent file:
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { KeycloakService, KeycloakAngularModule } from 'keycloak-angular';
import { initializer } from './app-init';

@NgModule({
  imports: [KeycloakAngularModule],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: initializer,
      multi: true,
      deps: [KeycloakService]
    }
  ]
})

For more information visit: https://www.npmjs.com/package/keycloak-angular

Upvotes: 1

Related Questions