Skip to content

Instantly share code, notes, and snippets.

@abn
Created October 12, 2017 13:02
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save abn/9929d6f0715657b359e3e74b295927a9 to your computer and use it in GitHub Desktop.
Save abn/9929d6f0715657b359e3e74b295927a9 to your computer and use it in GitHub Desktop.
A postman pre-request script to fetch a valid token from Red Hat SSO (Keycloak) and set it to a template variable to use in request headers.
// modify these configurations to work with your environment
var server = "https://sso.example.com";
var realm = "realm";
var resource = "client";
var username = "username";
var password = "url encoded password";
var url = `${server}/auth/realms/${realm}/protocol/openid-connect/token`;
var data = `grant_type=password&client_id=${resource}&username=${username}&password=${password}`;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
// set a global variable if we are not using environemnts
postman.setGlobalVariable('token', JSON.parse(this.responseText).access_token);
// use this if working within an environment
// postman.setEnvironmentVariable('token', JSON.parse(this.responseText).access_token);
}
});
xhr.open("POST", url);
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.send(data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment