title: Keycloak JavaScript API to get current logged in user
body: <p>We plan to use keycloak to secure a bunch of web apps, some written in Java, some in JavaScript (with React).   </p>
  
  <p>After the user is logged in by keycloak, each of those web apps needs to retrieve the user that is logged in and the realm/client roles that the user has.  </p>
  
  <ul>
  <li>For Java apps, we tried the keycloak Java API <code>(request -&gt; KeycloakSecurityContext -&gt; getIdToken -&gt; getPreferredUsername/getOtherClaims)</code>.   They seem to work fine</li>
  <li><p>For JavaScript apps, we tried the following code, but could not get Keycloak to init successfully (Note this is in web app code after the user is already authenticated by keycloak, the app is only trying to retrieve who logged in with what roles):</p>
  
  <pre><code>var kc = Keycloak({
      url: 'https://135.112.123.194:8666/auth',
      realm: 'oneRealm',
      clientId: 'main'
  }); 
  
  //this does not work as it can't find the keycloak.json file under WEB-INF
  //var kc = Keycloak('./keycloak.json'); 
  
  kc.init().success(function () {
      console.log("kc.idToken.preferred_username: " + kc.idToken.preferred_username);
      alert(JSON.stringify(kc.tokenParsed)); 
      var authenticatedUser = kc.idTokenParsed.name; 
      console.log(authenticatedUser);  
  }).error(function () {
      window.location.reload();
  });
  </code></pre></li>
  </ul>
  
  <p>I assume it would be fairly common that web apps need to retrieve current user info.  Anyone knows why the above code didn't work?</p>
  
  <p>Thanks.</p>