Get Access Token From Keycloak Using Postman
In this article, see how to get an access token from Keycloak using Postman.
Join the DZone community and get the full member experience.
Join For FreeThis 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"));
});
- This code will get a new token from Keycloak and extract the access_token from the response
and set into a collection variable {{access_token})
Now, save your collections, below is the sample screenshot
Create a New Request
- Create a new request
- Select the Authorization tab
- Select Type = Inherit auth from parent
- 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.
Opinions expressed by DZone contributors are their own.
Comments