Home > Mobile >  How can I get the user's email from Keycloak in this Angular app?
How can I get the user's email from Keycloak in this Angular app?

Time:02-01

I am working on an app in Angular 14 that requires authentication/authorization, reason for witch I use Keycloak Angular .

I need to get the currently logged in user's data from the application.

For this purpose, I have a service:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { User } from '../../../models/user';

@Injectable({
  providedIn: 'root'
})
export class UserFormService {

  httpOptions: object = {
    headers: new HttpHeaders({
      'Content-Type' : 'application/json'
    })
  }

  apiURL: string = 'http://localhost:8080';

  constructor(private http: HttpClient) { }
  
  public currentUserEmail: any;
  public currentUserData: any;
  
  public async getUserEmail(){
    let currentUser = await this.keycloakService.loadUserProfile();
    this.currentUserEmail =  currentUser.email;
  }

  public getUserByEmail(email: string): Observable<User>{
    return this.http.get<User>(`${this.apiURL}/getUserByEmail/${email}`, this.httpOptions);
  }

}

I use it in a component:

public getUserByEmail() {
    this.supplierFormService.getUserByEmail(this.currentUserEmail).subscribe(response => {
      this.currentUser = response;
      console.log('currentUser: ', response);
    });
}

In keycloak.init.ts I have:

import { KeycloakService } from 'keycloak-angular';

export function initializeKeycloak(keycloak: KeycloakService) {
    return () =>
      keycloak.init({
        config: {
          url: 'http://localhost:8085',
          realm: 'MyRealm',
          clientId: 'my-app'
        },
        initOptions: {
          onl oad: 'check-sso',
          silentCheckSsoRedirectUri:
            window.location.origin   '/assets/silent-check-sso.html'
        }
      });
}



 ngOnInit(): void {
    // Get user's email
    this.getUserEmail();
    // Get user's data by email
    this.getUserByEmail();
 }
  
  

The problem

Instad of returning the user's data, the service throws a 500 (Internal Server Error) and the email is undefined, as can be seen below:

http://localhost:8080/getUserByEmail?email=undefined
How do I fix this problem?

CodePudding user response:

You should sync those two calls, the getUserByEmail may be excecuted faster then currentUserEmail is set:

async ngOnInit(): void {
    // Get user's email
    await this.getUserEmail();
    // Get user's data by email
    this.getUserByEmail();
 }

CodePudding user response:

decode jwt token returned from keycloak. It contains current user data and Id Then get user by this id

  • Related