Integrate keycloak with angular

Joined
Mar 31, 2023
Messages
95
Reaction score
8
Integrating Keycloak with ngx-admin (nebular) involves a few steps. Here is a general outline of what you need to do:

  1. Install the Keycloak module in your ngx-admin application using npm. You can do this by running the following command in your terminal:
CSS:
npm install keycloak-angular [email protected]
  1. Next, import the KeycloakAngularModule into your application module:
JavaScript:
import { KeycloakAngularModule, KeycloakService } from 'keycloak-angular';

@NgModule({
  imports: [KeycloakAngularModule, ...],
  ...
})
export class AppModule {
  constructor(private keycloak: KeycloakService) {}
}
  1. In your app.component.ts file, initialize Keycloak:
JavaScript:
import { KeycloakService } from 'keycloak-angular';

export class AppComponent {
  constructor(private keycloakService: KeycloakService) {
    this.keycloakService.init({
      config: {
        url: 'https://<your-keycloak-server>/auth',
        realm: 'your-realm',
        clientId: 'your-client-id',
      },
      initOptions: {
        onLoad: 'login-required',
        checkLoginIframe: false
      },
      bearerExcludedUrls: []
    });
  }
}
  1. Once Keycloak is initialized, you can use it to authenticate users and retrieve their access tokens. You can add KeycloakGuard to your routing module to secure your application:
JavaScript:
import { KeycloakGuard } from 'keycloak-angular';

const routes: Routes = [
  {
    path: '',
    component: PagesComponent,
    canActivate: [KeycloakGuard],
    children: [
      ...
    ],
  },
  { path: '**', redirectTo: 'pages/dashboard' },
];
  1. Finally, you can use the keycloak.authenticated flag to check if the user is authenticated and the keycloak.getToken() method to retrieve their access token:
  2. JavaScript:
    import { KeycloakService } from 'keycloak-angular';
    export class SomeComponent {
      constructor(private keycloakService: KeycloakService) {}
    
      someMethod() {
        if (this.keycloakService.authenticated) {
          const token = this.keycloakService.getToken();
          // Use the token to make authenticated requests
        }
      }
    }
These are the basic steps to integrate Keycloak with ngx-admin (nebular). You may need to adjust the configuration to fit your specific use case.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top