typescriptangular8keycloak

KeyCloak Login leads to infinite loop


I have recently started using KeyCloak with Angular. My KeyCloak Docker is running on Port 8080, and my Angular-Application is running on 4200. Now when I access my app through the browser I get redirected to auth/realms/... with the appropriate redirect-url. Thats the expected behaviour so far. However, before the KeyCloak login page even loads I get redirected back to auth/realms/..., but this time my redirect-url is the old auth/realms/... I had just before.

The problem seems to be not KeyCloak itself, but my Angular implementation, since even if I disable my KeyCloak client or access the wrong client I get the same behaviour.

Now for some code. I have set up my KeyCloakOptions like this:

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

And the Service is initialized like this:

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));
  }
}

I have the suspicion that my app routing has something to do with the problem. It looks like this:

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 you need any further code please let me know, any help is apprechiated.

EDIT:

My first request looks 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 just realized that in the body of my response I am getting the index.html file of my Application, which is strange.


Solution

  • The way you have configured the Keycloak client, it never redirects to Angular. Instead, it redirects to itself (with a slightly different URL). The port number 4200 in the requested URL is the give-away.

    To fix, change the Keycloak configuration (in Angular). Change the line

      url: '/auth',
    

    to:

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