title: How to get current user name with Keycloak?
body: <p>I am trying to modify this <a href="https://github.com/keycloak/keycloak/tree/master/examples/demo-template/angular2-product-app" rel="nofollow noreferrer">example Angular2 application</a> to display the currently logged in user. First I tried getting it directly from <code>KeycloakService.tokenParsed.preferred_username</code> 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?</p>
  
  <p><strong>Solution</strong>: Based on @uchihaitachi's suggestion, here's the working method that I've added to my KeycloakService:</p>
  
  <pre><code>getPreferredUserName(): Promise&lt;string&gt; {
      return new Promise&lt;string&gt;((resolve, reject) =&gt; {
          if (KeycloakService.auth.authz.token) {
              KeycloakService.auth.authz.loadUserInfo().success((data) =&gt; {
                  resolve(&lt;string&gt;data.preferred_username);
              }).error(() =&gt; {
                  reject('Failed to get preferred user name');
              });
          }
      });
  }
  </code></pre>