Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
            });
        }
    });
}
like image 567
Thomas Leplus Avatar asked Oct 19 '25 17:10

Thomas Leplus


2 Answers

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 ;
}) 
like image 56
UchihaItachi-Inactive-Account Avatar answered Oct 22 '25 08:10

UchihaItachi-Inactive-Account


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

KeycloakService.auth.authz.loadUserProfile().success(function(data){
     $scope.username =  data.name ;
}) 
like image 36
nycynik Avatar answered Oct 22 '25 08:10

nycynik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!