Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save YPermitina/4f5465bbae978ee2ec96b26a2ad48420 to your computer and use it in GitHub Desktop.
Save YPermitina/4f5465bbae978ee2ec96b26a2ad48420 to your computer and use it in GitHub Desktop.
Скрипт для автоматического получения токена для Bearer авторизации.
// Для работы используются Variables: Username, Password, InformationSystemId
// В поле с токеном необходимо вставить ссылку на глобальную переменную {{token}}
const value = (key, defaultValue) => pm.globals.get(key) || defaultValue;
const setValue = (key, value) => pm.globals.set(key, value);
const variable = (key, defaultValue) => pm.variables.get(key) || defaultValue;
const setVariable = (key, value) => pm.variables.set(key, value);
const getTimeStamp = (expires_in = 0) => {
if (expires_in == 0) return new Date();
else return new Date(expires_in);
}
const sendRequest = (urlencoded) => {
const request = {
url: `${variable('baseUrl')}/api/identity/login`,
method: 'POST',
header: 'Content-Type:application/json',
body: {
mode: 'application/json',
raw: JSON.stringify(urlencoded)
}
};
pm.sendRequest(request, (err, res) => {
const { token, expiration } = res.json();
setValue('token', token);
setValue('expiration', getTimeStamp(expiration));
setValue('tokenUser', variable('Username'));
});
}
const sendLoginRequest = () => {
console.log('Send login request');
sendRequest(
{
"Password": variable('Password'),
"Username": variable('Username'),
"InformationSystemId": variable('InformationSystemId')
}
);
console.log(token);
}
const token = value('token');
const expiration = getTimeStamp(value('expiration'));
const tokenUser = value('tokenUser');
console.log(token);
console.log(expiration);
// Получаем новый токен, если токена нет, истек срок или сменился пользователь
if(!token || (expiration <= getTimeStamp()) || expiration == undefined || tokenUser != variable('Username'))
{
sendLoginRequest();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment