mauriciovigolo / keycloak-angular

Easy Keycloak setup for Angular applications.
MIT License
730 stars 280 forks source link

App without app.modules.ts, only standalone components #474

Closed ProfEibe closed 1 year ago

ProfEibe commented 1 year ago

Bug Report or Feature Request (mark with an x)

- [ ] bug report -> please search for issues before submitting
- [X] feature request

Versions.

Angular 15+

Desired functionality.

Would be great to have a way to secure an Angular-App with the new Standalone Components. An example without an app.module.ts would be great and what would be the best way to "bootstrap" such an application to ensure keycloak is loaded first.

tricsusz commented 1 year ago

Hello @ProfEibe

It works fine for me.

This is my main.ts file (everything else is the same as here):


import {
  APP_INITIALIZER,
  enableProdMode,
  importProvidersFrom,
} from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { RouteReuseStrategy, provideRouter } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';

import { routes } from './app/app.routes';
import { AppComponent } from './app/app.component';
import { environment } from './environments/environment';
import { KeycloakAngularModule, KeycloakService } from 'keycloak-angular';

if (environment.production) {
  enableProdMode();
}

function initializeKeycloak(keycloak: KeycloakService) {
  return () =>
    keycloak.init({
      config: {
        url: 'http://.....',
        realm: '...',
        clientId: '....,
      },
      initOptions: {
        onLoad: 'check-sso',
        silentCheckSsoRedirectUri:
          window.location.origin + '/assets/silent-check-sso.html',
      },
    });
}

bootstrapApplication(AppComponent, {
  providers: [
    importProvidersFrom(KeycloakAngularModule),
    {
      provide: APP_INITIALIZER,
      useFactory: initializeKeycloak,
      multi: true,
      deps: [KeycloakService],
    },
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    importProvidersFrom(IonicModule.forRoot({})),
    provideRouter(routes),
    importProvidersFrom(HttpClientModule),
  ],
});```
mauriciovigolo commented 1 year ago

Hi @tricsusz, thanks for sharing the solution. I think we could improve the docs or example with something similar for the newer versions of Angular. I will close this issue for now. Thank you all!