How to get current user name with Keycloak?

不羁的心 提交于 2019-12-06 12:58:27

问题


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');
            });
        }
    });
}

回答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 ;
}) 



回答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 ;
}) 



回答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;
        })
    }
}


来源:https://stackoverflow.com/questions/40986480/how-to-get-current-user-name-with-keycloak

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!