Created
October 12, 2017 13:02
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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