'How to get current user name with Keycloak?

I am trying to modify this example Angular2 application to display the currently logged in user. First I tried getting it directly from KeycloakService.tokenParsed.preferred_username but it doesn't seem to exist out of the box with the example code. My guess is that I have to add a function to the KeycloakService to go fetch the user name separately but I am not sure that it is the simplest approach and how to go about this?

Solution: Based on @uchihaitachi's suggestion, here's the working method that I've added to my KeycloakService:

getPreferredUserName(): Promise<string> {
    return new Promise<string>((resolve, reject) => {
        if (KeycloakService.auth.authz.token) {
            KeycloakService.auth.authz.loadUserInfo().success((data) => {
                resolve(<string>data.preferred_username);
            }).error(() => {
                reject('Failed to get preferred user name');
            });
        }
    });
}


Solution 1:[1]

I am afraid I have not worked on the Typescript before , but I use the loadUserInfo() method . Suppose you want to load get the value in a scope varaable name userName :

then this should work fine I suppose:

This code works

KeycloakService.auth.authz.loadUserInfo().success(function(data){
  $scope.userName =  data.name ;
}) 

Solution 2:[2]

The accepted answer no longer works in Keycloak (we are using 3.x)

KeycloakService.auth.authz.loadUserProfile().success(function(data){
     $scope.username =  data.name ;
}) 

Solution 3:[3]

Keycloak loadUserProfile my sample code. It's working perfectly try this :

keycloak.service.ts

loadProfile(): Promise<any> {
    return new Promise<any>((resolve, reject) => {
      if (KeycloakService.auth.authz.token) {
        KeycloakService.auth.authz
          .loadUserProfile()
          .success(data => {
            resolve(<any>data);
          })
          .error(() => {
            reject('Failed to load profile');
          });
      } else {
        reject('Not loggen in');
      }
    })
  }

app.component.ts

export class AppComponent implement OnInit {
    private agentProfile: any = {};

    constructor(private kc: KeycloakService) { }

    ngOnInit() {
        this.kc.loadProfile().then(user => {
            this.agentProfile = user;
        })
    }
}

Solution 4:[4]

If anyone looking for more cleaner way to get current user name with Keycloak..
in your xxxx.component.ts

ngOnInit() {
this.loadProfile().then(user => {
    console.log(user.username)
})
}

loadProfile(): Promise<any>{
return new Promise<any>((resolve, reject) => {
  if(this.auth.isLoggedIn()){
    this.auth.loadUserProfile()
    .then(data => resolve(data))
    .catch(error => console.log(error))
  } else{
    console.log('user not logged in')
  }
})
}

Solution 5:[5]

import {KeycloakService} from 'keycloak-angular';

constructor(private keycloakService: KeycloakService) {}

ngOnInit(): void {
   console.log(this.keycloakService.getUsername());
   let userDetails = await this.keycloakService.loadUserProfile();
   console.log(userDetails);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adam Michalski
Solution 2 nycynik
Solution 3 Chandru
Solution 4 Nisal Pubudu
Solution 5