How to get current user name with Keycloak?

孤街醉人 提交于 2019-12-04 19:21:46
UchihaItachi

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

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

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

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