What is the best way to integrate my Angular keycloak setup with an idphint attribute?

I have successfully integrated the angular keycloak adapter from https://www.npmjs.com/package/keycloak-angular to connect with our keycloak server.

Currently, I am exploring the idphint attribute to redirect the request to a different identity provider.

Question: When using the login() method, there is an option to include the idphint attribute. However, I am unsure how to incorporate this into my existing implementation. Any tips?

My current setup:

export function initializeAuth(authService: KeycloakAuthenticationService): () => void {
  return () => authService.init({
    config: {
      url: KEYCLOAK_AUTH_URL,
      realm: 'Example-REALM',
      clientId: 'angular-client'
    },
    initOptions: {
      onLoad: 'login-required',
      checkLoginIframe: false
    }
  });
}
@NgModule({
 ...
  providers: [
    {provide: APP_INITIALIZER, useFactory: initializeAuth, multi: true, deps: [KeycloakAuthenticationService]}
  ]
...
})

Answer №1

Encountering the same issue recently led me to conduct some research that I believe may be helpful for others facing a similar problem. It appears that providing the idpHint when invoking the login() function after initializing the adapter but before logging in is crucial. Failure to do so might result in the provider not being included in the loginUrl during the first login attempt. One possible workaround could involve using the init() method to manually check the login status and decide whether to log in or not...

After exploring various options, I opted for a solution where I modified the login method to include my idpHint in a more direct manner:

const keycloakInit: KeycloakInit = {
  onLoad: 'login-required',
  flow: 'implicit'
};
const keycloakLoginParams = {
  idpHint: 'XXX-YYY'
};

export const environment: EnvironmentData = {
  production: false,
  keycloakJsUrl,
  keycloakConfig,
  keycloakInit,
  keycloakLoginParams,
  ...
};
  private initKeycloak(resolve, reject) {
    if (!environment.keycloakConfig) {
      reject('keycloak config missing, but init triggered. reject');
    }

    this.keycloakAuth = new Keycloak(environment.keycloakConfig);

    if (environment.keycloakLoginParams) {
      // wrap an custom function around original login to support idpHint
      const kcLogin = this.keycloakAuth.login;
      this.keycloakAuth.login = (options) => {
        Object.assign(options, environment.keycloakLoginParams);
        kcLogin(options);
      };
    }

    this.keycloakAuth.init(environment.keycloakInit || {onLoad: 'login-required'})
      .success(() => {
        const tokenParsed = this.tokenParsed;
        this.user = this.createUserObject(tokenParsed);
        console.log('logged in', this.user, tokenParsed);
        resolve();
      })
      .error((resp) => {
        reject(resp.error + ': ' + resp.error_description);
      });

    // called when the access token is expired. we use implicit flow, just show login mask
    this.keycloakAuth.onTokenExpired = () => {
      this.redirectToLogin();
    };

  }

Answer №2

One improvement that keycloak-angular is working on is adding support for the idpHint by including KeycloakLoginOptions in the init method of keycloak-angular. You can track the progress of this enhancement here: https://github.com/mauriciovigolo/keycloak-angular/issues/334

Once this issue is resolved, we will be able to streamline our code by utilizing the KeycloakService.init(...) method from keycloak-angular instead of creating a custom init method.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to configure routerLinkActive specifically for these routes?

My website has a navigation bar with the following items: Users, Categories, Products, etc. The routes are set as Main/Users, Main/Categories. I have successfully highlighted the items using routerLinkActive, however I also want to highlight the Users item ...

Error in Angular: Trying to access the property 'id' of an undefined value

I am facing an issue with a div tag in my HTML file. The code snippet looks like this: <div *ngIf="chat.asReceiver.id != user?.id; else otherParty"> Unfortunately, it always returns the following error: ERROR TypeError: Cannot read propert ...

Angular2 (RC5) global variables across the application

I am seeking a solution to create a global variable that can be accessed across different Angular2 components and modules. I initially considered utilizing dependency injection in my `app.module` by setting a class with a property, but with the recent angu ...

Ways to dynamically insert a new row into a table based on user input in a Postman-like reactive table

Is there a way to dynamically insert a row when a single character is entered into an input field in the header tab, similar to how Postman functions? 1) If a user types any single character in the td of the first row, then a new row should be added below ...

Tips on preventing state sharing in Angular applications

Delving into the world of Angular has presented me with an intriguing issue. I've crafted a component dedicated to displaying a dialog, complete with its own template (HTML), CSS, and TypeScript files. Whenever a user clicks on an item within a list ...

Retrieving the value of a checkbox when clicked in Angular 2

I am trying to use ngModel binding to check the status of a checkbox. After calling console.log(activeCheckbox);, I can see that the ngmodel and its value property are set to true in the console. However, when I immediately call console.log(activeCheck ...

Preflight request response failed access control check due to absence of 'Access-Control-Allow-Origin' header

I encountered an error while attempting to upload a file and store it in a database using Angular4 as the front end. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the ...

Navigational module and wildcard for routes not located

I have my routing configuration structured as follows: app-routing const routes: Routes = [ { path: 'login', loadChildren: 'app/modules/auth/auth.module#AuthModule' }, { path: '', redirectTo: 'dash ...

Sign up for the completion event within the datetime picker feature in Ionic 2

How can I subscribe to the "done" event in Ionic2, where I want to trigger a function after selecting a date? <ion-icon class="moreicon" name="funnel"> <ion-datetime type="button" [(ngModel)]="myDate" (click)="getData()"></ion-datetime> ...

Sending JSON Object using NavController

I am trying to send a JSON Object to another Page in my Ionic 2 application. However, when I attempt to do so, I encounter the error: Cannot read property 'user' of undefined. While researching for a solution, I came across a similar question ...

The Angular API request is continuously retrieving data every single second

I recently inherited some Angular/ng-bootstrap code that included a table with static data, which was functioning perfectly. However, the requirement now is to fetch the data from an API call. In an attempt to modify it accordingly, I referred to an answer ...

Storing response data as a variable in TypeScript with Angular 2 can be achieved by declaring a variable

I am unfamiliar with TypeScript and need assistance. After performing a POST request, I received an _id that I now need to use to execute a PUT function for play pause. When the play pause button is clicked, the response should be sent to the server. Below ...

Applying the power of Angular function binding within .html() function in d3 visualizations

I am attempting to create a clickable d3 foreignObject span that triggers a function in the component TypeScript file. Below is a snippet of the code I have been working on: .append("foreignObject") .attr("x", x) .attr("y" ...

"Encountering an error when trying to access undefined property in templates

The content displayed in my component template is not what I expected when using @Output to pass an object from a parent container. While attempting to bind {{selectedMovDetail|json}} in the template, the output shows as { "name": "The Walking Dead","rati ...

Capturing Angular 4 Screenshots with html2canvas

Is there a way to capture and send a screenshot using html2canvas in Angular 4 via an HTTP POST request? Component import { Component, OnInit, NgZone } from '@angular/core'; import { Router, ActivatedRoute, Params } from '@angular/rout ...

I am experiencing issues with the search feature in angular and node.js that is not functioning properly

Need assistance with debugging this code. I am currently working on adding search functionality to my Angular web page. However, when testing the code in Postman, I keep receiving the message "NO USER FOUND WITH USERNAME: undefined". Additionally, on the w ...

Setting dynamic values for SASS mixins in Angular 2 with Ionic 2

In my SCSS file, I have created a mixin to generate a progress bar. @mixin progressBarMix($name, $size, $perc, $color, $colorBack) { .progressBarWrapper { &#{$name} { $sizeFill: $size / 100 * $perc; .progressBarEndFilled { b ...

Trouble encountered during installation of Angular CLI: module.js - code 549

I recently encountered issues with Angular-CLI, so I decided to update it using the command $ npm install -g @angular/cli. However, after doing so, I am facing a new error message. Can anyone provide assistance with this problem? module.js:549 throw err ...

Learn how to send error logs from an Angular frontend to the backend using a custom API or any other method to store them in the Serilog table in MSSQL

Is there a way to log errors from an Angular frontend to a backend using a custom API or any other method that can send the data to Serilog's SQL sink table in MSSQL? My application utilizes multiple APIs from various third-party resources, and I need ...