Krishnan

Software Developer

Get Access Token from Keycloak using Postman

This post will help you to automate getting access token from keycloak and added into request param before each API hits server.

To Get Access Token Using Postman (For Testing)

Create new Collection in postman

  • Click new collection button in postman
  • Select variable tab and add the below variables

    • client_id : <Copy the client id from your realm setting in KC>
    • client_secret : <Make sure you copy the right secrets for the client>
    • scope : type ‘openid’
    • token_endpoint : <_http://KEYCLOAK-SERVER_URL/auth/realms/REPLACE_WITH_YOUR_REALM_NAME/protocol/openid-connect/token_>
    • access_token : <Leave it blank, this will be populated by pre-request script>

    variable

  • Go to authorization tab

    • Select Type = Bearer Token
    • Token = {{access_token}}

    authorization * Now go to pre-request scripts tab and paste the following code

    var client_id      = pm.collectionVariables.get("client_id");
    var client_secret = pm.collectionVariables.get("client_secret");
    var token_endpoint = pm.collectionVariables.get("token_endpoint");
    var scope          = pm.collectionVariables.get("scope");
    
    var details = {
    "grant_type" : "client_credentials",
    "scope" : scope
    }
    
    var formBody = [];
    for (var property in details) {
    var encodedKey = encodeURIComponent(property);
    var encodedValue = encodeURIComponent(details[property]);
    formBody.push(encodedKey + "=" + encodedValue);
    }
    formBody = formBody.join("&");
    
    pm.sendRequest({
    url: token_endpoint,
    method: 'POST',
    header: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization' :'Basic ' + btoa(client_id+":"+client_secret)
          },
      body: formBody
    },  function(err, response) {
    const jsonResponse = response.json();
    console.log(jsonResponse);
    pm.collectionVariables.set("access_token", jsonResponse.access_token);
    console.log(pm.collectionVariables.get("access_token"));
    
    }); 
    

Pre request scripts

  • This code will get a new token from keycloak and extract the access_token from response and set into a collection variable {{access_token}}

  • Now, save your collections


Create new Request

  • Create a new request
  • Select Authorization tab

    • Select Type = Inherit auth from parent

    Sample Request

  • Add your headers, request body if any

  • Make sure you save the request under the collection that you created above

  • Now try running the script.


Key Points

  • This script will be executed before each request in this collection and attach the access_token to the request.