This post will help you to automate getting an access token from Keycloak and added into request param before each API request hits the server. Keycloak is an open-source software product to allow single sign-on with Identity and Access Management aimed at modern applications and services. Read here to know more about Keycloak.
To Get Access Token Using Postman (For Testing)
Create New Collection in Postman
- Click the new collection button in postman
- Select the 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>
- Go to the authorization tab
- Select Type = Bearer Token
- Token = {{access_token}}
- Now go to the pre-request scripts tab and paste the following code
xxxxxxxxxx
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"));
});