Endless cycle occurs when attempting to login to KeyCloak

Recently, I have delved into the realm of using KeyCloak with Angular. The KeyCloak Docker is up and running on Port 8080 while my Angular application takes its place on 4200. As I access my app through the browser, I find myself redirected to auth/realms/... with the correct redirect URL, as expected. However, before the KeyCloak login page fully loads, I am swiftly redirected back to the same auth/realms/..., but this time with the old redirect URL that was present just moments ago.

The root of the issue doesn't seem to lie within KeyCloak itself, rather it appears to be a glitch in my Angular implementation. This behavior persists even if my KeyCloak client is disabled or if an incorrect client is accessed.

To provide some insight into the code aspect, here's how I configured my KeyCloakOptions:

export const keycloakOptions: KeycloakOptions = {
  config: {
    url: '/auth',
    realm: 'bookstore',
    clientId: 'bookstore-front-end'
  },
  initOptions: {
    onLoad: 'login-required',
    checkLoginIframe: false
  },
  enableBearerInterceptor: true,
  bearerExcludedUrls: ['/assets']
};

Furthermore, the initialization of the Service is done in the following manner:

export class AppModule implements DoBootstrap {

  public ngDoBootstrap(appRef: ApplicationRef): void {
    keycloakService
      .init(keycloakOptions)
      .then(() => {
        console.log('[ngDoBootstrap] bootstrap app');
        appRef.bootstrap(AppComponent);
      })
      .catch(error => console.error('[ngDoBootstrap] init Keycloak failed', error));
  }
}

A suspicion creeps in regarding the involvement of my app routing in causing this hiccup. Below is a brief overview of how my routes are structured:

const routes: Routes = [
  // home route protected by auth guard
  {path: 'books', component: BooksComponent, canActivate: [AuthGuard]},

  // otherwise redirect to home
  {path: '', redirectTo: 'books', pathMatch: 'full'}
];

If any additional segments of code are required for analysis, feel free to ask for them. Any assistance on this matter would be greatly appreciated.

EDIT:

The initial request I make presents itself like this:

http://localhost:4200/auth/realms/bookstore/protocol/openid-connect/auth?client_id=bookstore-front-end&redirect_uri=http%3A%2F%2Flocalhost%3A4200%2F&state=c530f55a-b21e-43c3-8e1c-a3beb134c9ee&response_mode=fragment&response_type=code&scope=openid&nonce=0c359787-92e7-4d6d-9578-a65da686b046

However, I've just noticed that within the body of my response, I'm being served the index.html file of my application, which strikes me as peculiar.

Answer №1

The Keycloak client is set up in a way that it does not redirect to Angular as expected, but redirects back to itself with a slightly modified URL. You can easily spot this by the port number 4200 present in the requested URL.

To resolve this issue, you need to make changes to the Keycloak configuration within your Angular application. Update the following line:

  url: '/auth',

to:

  url: 'http://localhost:8080/auth',

Answer №2

Today, I encountered a similar issue but it was not exactly the same as described by the author. It turned out that the problem stemmed from React strict mode being enabled in my development environment.

I resolved the issue by removing the <React.StrictMode> and ensuring that useEffect() had [] as its dependency. This fixed the issue for me because we only needed to call keycloak.init() once.

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

WebStorm error: The type of argument 'this' cannot be assigned to the parameter type 'ObjectConstructor

After implementing the constructor below in TypeScript, I encountered an error stating that the argument type 'this' is not compatible with the parameter type 'ObjectConstructor'. Strangely enough, the CLI didn't flag any errors. U ...

Centralize all form statuses in a single component, conveniently organized into separate tabs

I am working on a component that consists of 2 tabs, each containing a form: tab1.component.ts : ngOnInit() { this.params = getParameters(); } getParameters() { return { text : 'sample' form: { status: this.f ...

TypeScript is unable to locate the identifier 'async' within the code

While working with TypeScript, I encountered an error: [ts] Cannot find name 'async' Here is the code snippet causing the issue: async someAsyncCode() { let asyncFn = () => { return new Promise((resolve: Function) => { resolv ...

Why won't my code work with a jQuery selector?

I'm struggling to retrieve the value from a dynamically generated <div> using jQuery. It seems like the syntax I'm using doesn't recognize the div with an id tag. The HTML code is stored in a variable, and below is a snippet of code w ...

Tips for passing an object as an argument to a function with optional object properties in TypeScript

Consider a scenario where I have a function in my TypeScript API that interacts with a database. export const getClientByEmailOrId = async (data: { email: any, id: any }) => { return knex(tableName) .first() .modify((x: any) => { if ( ...

Tips for selecting specific types from a list using generic types in TypeScript

Can anyone assist me in creating a function that retrieves all instances of a specified type from a list of candidates, each of which is derived from a shared parent class? For example, I attempted the following code: class A { p ...

Defining a TypeScript conditional return type that may include undefined

Here is the function I currently have, but unfortunately I encountered the following error: Type '(T & undefined) | { obj: T & ({} | null); }' is not assignable to type 'T extends undefined ? undefined : { obj: T; }'. Type & ...

What is the best way to declare a TypeScript type with a repetitive structure?

My data type is structured in the following format: type Location=`${number},${number};${number},${number};...` I am wondering if there is a utility type similar to Repeat<T> that can simplify this for me. For example, could I achieve the same resul ...

Issue with variable not being populated by Observable

Although my observable is sending back the correct object, I am facing an issue where the data is not being stored against a local variable. import { Component, OnInit, OnDestroy } from '@angular/core'; import { LookupListsService } from '.. ...

Modifying the functionality of "use-input" in Vue.js

Currently, I am utilizing vue.js along with typescript to create an input field that allows users to either choose items from a drop-down menu or manually type in their own input. There are various scenarios where custom input might be allowed or where onl ...

Using Typescript generics to deduce the type from the second parameter for utilization in the first slot

Here is the code snippet I'm working with: export type Subscribe<T extends object> = <U>( listener: (slice: U) => void, selector: (state: T) => U, ) => void // The actual implementation is not relevant const subscribe = {} as ...

State Management: Efficient Techniques for Handling Complex Nested States using Immer and TypeScript

I am currently utilizing Zustand alongside Immer to establish a store within the project I am currently developing. The store has a deeply nested state consisting of Series objects with the following structure: { id: 0, metaData: {}, ...

Is it possible to conditionally remove the parent upon the loading of the Router?

Below is the content from my component.html file: <content-placeholder></content-placeholder> <router-outlet></router-outlet> I would like to know if there is a way to hide or remove the <content-placeholder></content-pla ...

Transform the date format from Google Forms to TypeScript

I am currently facing an issue with a Google Form connected to a Google Spreadsheet. The date format in the spreadsheet appears as follows when a response is received: 20/02/2023 18:58:59 I am seeking guidance on how to convert this date format using Type ...

Learn how to dynamically activate an icon in Angular to enhance user interaction

HTML Code: The Zoom Component <div class="zoom py-3"> <i nz-icon nzType="minus" (click)="zoomToggle(false)" nzTheme="outline"></i><br> <i nz-icon nzType="plus" (click)=&q ...

Is there a way for me to receive the status code response from my backend server?

My component makes a call to a servlet, which then sends a POST HTTP request to the backend (using Spring Boot). I want the backend to return the status of the POST request that was sent earlier. This is my code: res= this.CS.postcompetenze(this.comp) Th ...

Leveraging the power of React's callback ref in conjunction with a

I'm currently working on updating our Checkbox react component to support the indeterminate state while also making sure it properly forwards refs. The existing checkbox component already uses a callback ref internally to handle the indeterminate prop ...

Angular 6's observable variable doesn't properly support Ng If functionality

I successfully implemented server-side pagination in the Angular6 material data grid following the instructions from this link. Now, I am facing an issue where I want to display a "No Data Found" message if the response dataset is empty. I tried using ngI ...

What are the best practices for utilizing Angular form validation effectively?

I am currently working on implementing form validation in my project. I have created a basic login form and now I want to validate the input fields before submitting them to the server, while also providing visual feedback to the user if the inputs are inv ...

Is it TypeScript's return type a double arrow (Observable)?

I'm having a hard time understanding this: const loadData: (detailsStore: RecipeDetailsStore) => (source$: Observable<string>) => Observable<RecipeDetails> How should I interpret this? My understanding is: loadData is a function t ...