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 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: '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(); });
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?
Thanks.