简体   繁体   中英

Angular role based authentification keycloak and SpringBoot

I would like to set up an authentication between my Angular front and my SpringBoot backend. I have a SpringBoot authentication server configured with SpringBoot and functional. The Front can authenticate to Keycloak and have access to the SpringBoot API.

The problem is that I want to know how to know if the user is logged in or not to display the login button.

And the second thing is that I would like some pages to be displayed and others not, depending on the user's role.

And as a bonus if you know... I would like to display some parts of a DOM depending on the user's role.

(this is the first time I set up this system... thanks for the help) No problem on Keycloak and Spring side, connection is OK and redirection to Angular OK too. Bearer saved OK

app.component.ts

import { Component } from '@angular/core';
import { OAuthService, NullValidationHandler, AuthConfig } from 'angular-oauth2-oidc';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  
  constructor(private oauthService: OAuthService) {
    this.configure();
  }
authConfig: AuthConfig = {
    issuer: 'http://localhost:8081/auth/realms/api-team', // Keycloak Server
    redirectUri: window.location.origin + "/api-team", // My SpringBoot
    clientId: 'api-team-client-angular',
    scope: 'openid profile email offline_access api-angular',
    responseType: 'code',
    // at_hash is not present in JWT token
    // disableAtHashCheck: true,
    showDebugInformation: true
  }
  
  public login() {
    this.oauthService.initLoginFlow();
  }
  
  public logoff() {
    this.oauthService.logOut();
  }
  
  private configure() {
    this.oauthService.configure(this.authConfig);
    this.oauthService.tokenValidationHandler = new  NullValidationHandler();
    this.oauthService.loadDiscoveryDocumentAndTryLogin();
  }
}

Just a test.. app.component.html

<router-outlet>
  <button class="btn btn-default" (click)="login()">
    Login
  </button>
  <button class="btn btn-default" (click)="logoff()">
    Logout
  </button>
    <app-loader></app-loader>
</router-outlet>

One of my router

export const MaterialRoutes: Routes = [
    {
        path: '',
        children: [
            // {
            //     path: 'services-namespace',
            //     component: ServicesProjetComponent,
            //     data: {
            //         title: "Composants d'un projet",
            //         urls: [
            //             { title: 'Dashboard', url: '/dashboard1' },
            //             { title: "Composants d'un projet" }
            //         ]
            //     }
            // },
            {
                path: 'namespaces',
                component: ProjetsComponent,
                data: {
                    title: "Liste des Projets",
                    urls: [
                        { title: 'Dashboard', url: '/dashboard1' },
                        { title: "Liste de Projets" }
                    ]
                }
            }

All you need to add is Angular guards (and maybe an authentication service).

I've setup a minimal mono-repo for a meetup about Open ID with very similar stack: spring RESTful API (ok it's servlet, not reactive), Angular front-end and Keycloak authorization server.

I suggest you clone and hack it. For Angular specific parts, have a close look at:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM