Skip to content

Instantly share code, notes, and snippets.

@benjaminvanrenterghem
Last active July 22, 2022 19:58
Show Gist options
  • Save benjaminvanrenterghem/4a625c8f8b8e221dfa34d522c37adaaa to your computer and use it in GitHub Desktop.
Save benjaminvanrenterghem/4a625c8f8b8e221dfa34d522c37adaaa to your computer and use it in GitHub Desktop.
Custom_Postman_PreRequest_Script____ASP_NET_API_Tutorial
let jwtFetchError = "Failed to gather JWT Token - check if your API is running, select a Postman Environment -- and make sure to have added the 2 default accounts (query can be found in prerequest script -or- in the documentation)";
if(JSON.parse(pm.environment.get("LOGIN_WITHOUT_AUTH"))){
console.log("No JWT Token was fetched due to the selected Postman Environment");
return;
}
pm.sendRequest({
rejectUnauthorized: false,
url: pm.environment.get("API_HTTP_PROTOCOL") +
pm.environment.get("API_HOST") + ":" +
pm.environment.get("API_PORT") +
pm.environment.get("API_LOGIN_PATH"),
method: 'POST',
header: 'Content-Type:application/json',
body: {
mode: 'application/json',
raw: JSON.parse(pm.environment.get("LOGIN_WITH_INVALID_CREDS")) ?
pm.environment.get("API_LOGIN_INVALID_CREDS") :
JSON.parse(pm.environment.get("LOGIN_AS_MANAGEMENT")) ?
pm.environment.get("API_LOGIN_ADMIN_CREDS") :
pm.environment.get("API_LOGIN_USER_CREDS")
}
}, function (err, res) {
if(err) {
console.error(jwtFetchError);
}
if(res) {
if(!res.json().content?.length){
console.error(jwtFetchError);
}
let token = res.json().content[0];
console.log("Successfully received JWT Token - setting header", res.json())
pm.request.headers.add("Authorization: Bearer "+token);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment