[keycloak-user] keycloak APIs to retrieve logged-in user

shimin q shimin_q at yahoo.com
Mon Jul 10 11:56:47 EDT 2017


Hi, 
I am new to keycloak (sorry if the answer to my question seems obvious!).  We plan to use keycloak to secure a bunch of web apps, some written in Java, some in JavaScript (with React).   
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.  
   
   - For Java apps, we tried the keycloak Java API (request -> KeycloakSecurityContext -> getIdToken -> getPreferredUsername/getOtherClaims).   They seem to work fine

   
   - For JavaScript apps, we are hitting roadblocks.   What APIs would you recommend to use specifically?  Do you have any example code for JavaScript apps?   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):   


var kc = Keycloak({    url: 'https://135.112.123.194:8666/auth',    realm: 'rtna',    clientId: 'main'}); //var kc = Keycloak('./keycloak.json'); //this does not work as it can't find the keycloak.json file under WEB-INF//kc.loadUserInfo();var userid = kc.subject;console.log("user id " + userid);
kc.init({ onLoad: 'login-required' }).success(function () {    console.log("===================================");    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();  });

Please advise.  Thank you!!



More information about the keycloak-user mailing list