Search code examples
keycloakkeycloak-serviceskeycloak-rest-api

From Keycloak Login : How can I get the Bearer Token from KEYCLOAK_IDENTITY/KC_RESTART cookie


I have a UI application running on ReactJS. For login we are redirecting it to keycloak login page.

  • After providing the username and password on keycloak login page,
  • I am seeing that KEYCLOAK_IDENTITY/KC_RESTART are set.
  • I have validated the KEYCLOAK_IDENTITY cookie at JWI.IO website as well. it is showing below details

{ "cid": "abc-client", "pty": "openid-connect", "ruri": "https://10.10.10.10:3001/", "act": "AUTHENTICATE", "notes": { "scope": "openid", "iss": "https://10.10.10.10:8445/auth/realms/abcrealm", "response_type": "code", "redirect_uri": "https://10.10.10.10:3001/", "state": "879b6182-dca0-495c-8644-5b2ac032b5e4", "nonce": "1e263181-2313-45ea-962a-175fd58c6d75", "response_mode": "fragment" } }

  • Now My question is: how can I get the bearer token from this "KEYCLOAK_IDENTITY" cookie. I need the bearer token for all my next authorization checks on REST APIs because every user has different roles and can perform operations only if their profile has certain roles.

In other words, I just want to do a check/validate that provided KEYCLOAK_IDENTITY token is having a valid roles in the profile or not.


Solution

  • Use keycloak-js for validating the login. Initialise keycloak with keycloak config json. Make sure you are giving config of public client (No secret required). Once initialized, keycloak object will have both token and tokenParsed. It also has bunch of other useful functions. Check their docs.

    import Keycloak from 'keycloak-js';
    const keycloak = Keycloak('/keycloak.json');
    keycloak.init({
      onLoad: 'login-required',
    }).then((authenticated) => {
      if (authenticated) {
        const token = keycloak.token;
        const tokenParsed = keycloak.tokenParsed;
      
      }
    }