授权载体令牌的邮递员预请求脚本

时间:2019-11-09 01:13:09

标签: javascript postman postman-collection-runner postman-pre-request-script

我正在尝试制作脚本以生成用于集合的身份验证承载令牌。因此我不必每次都传递令牌,而我将从父级继承auth。但是我不知道我在脚本中哪里写错了,我无法生成令牌,这给了我错误

There was an error in evaluating the Pre-request Script:  Error: No data, empty input at 1:1 ^

这是我的脚本

var expiresOn = pm.variables.get('ExpiresOn');
    if (!expiresOn || new Date(expiresOn) <= new Date()) {

    var clientId = '565v7677676vfdrd';
    var apiToken =  '6565fdvdrdfd';

    var request = {
        url: 'http://.../auth/token',
        method: 'POST',
        header: 'Content-Type:application/Json',
        body: {
            mode: 'application/json',
            raw:  clientId + apiToken
        }
    };
            }
        };

        pm.sendRequest(request, function (err, res) {
            if (res !== null) {
                var json = res.json();
                pm.environment.set('Access_Token', json.access_token)

                var expiresOn = new Date(0);
                expiresOn.setUTCSeconds(json.expires_on);
                pm.environment.set('ExpiresOn', expiresOn);
            }
        });
    }

3 个答案:

答案 0 :(得分:0)

const echoPostRequest = {
  url: 'https://example.com/sign_in?client_id=dbdsA8b6V6Lw7wzu1x0T4CLxt58yd4Bf',
  method: 'POST',
  header: 'Accept: application/json\nUser-Agent: Example/2019.10.31-release (Android 6.0.1; LGE Nexus 5)\nUDID: 1d2c7e65f34b3882f8e42ab8d6a82b4b\nContent-Type: application/json; charset=utf-8\nHost: api-mobile.example.com',
  body: {
    mode: 'application/json',
    raw: JSON.stringify(
        {
        	client_id:'dbdsA8b6V6Lw7wzu1x0T4CLxt58yd4Bf',
        	client_secret:'aBK1xbehZvrBw0dtVYNY3BuJJOuDFrYs',
        	auth_method:'password',
        	create_if_not_found:false,
        	credentials:{identifier:'username',password:'pass'},
        	signature:'2:a899cdc0'
        })
  }
};

var getToken = true;

if (!pm.environment.get('accessTokenExpiry') || 
    !pm.environment.get('currentAccessToken')) {
    console.log('Token or expiry date are missing')
} else if (pm.environment.get('accessTokenExpiry') <= (new Date()).getTime()) {
    console.log('Token is expired')
} else {
    getToken = false;
    console.log('Token and expiry date are all good');
}

if (getToken === true) {
    pm.sendRequest(echoPostRequest, function (err, res) {
    console.log(err ? err : res.json());
        if (err === null) {
            console.log('Saving the token and expiry date')
            var responseJson = res.json();
            pm.environment.set('currentAccessToken', responseJson.access_token)
           
            var expiryDate = new Date();
            expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);
            pm.environment.set('accessTokenExpiry', expiryDate.getTime());
        }
    });
}
上面的示例是一个邮递员预先请求脚本,用于获取access_token和令牌的到期时间。我认为这个例子将帮助您解决问题。 请检查邮递员的控制台 在Windows上按Ctrl + Alt + C(在Mac上为Cmd + Alt + C)来打开Postman控制台。

enter image description here

答案 1 :(得分:0)

语法错误

运行脚本时出现以下错误:

There was an error in evaluating the Pre-request Script:  SyntaxError: Unexpected token ';'

应该正确执行以下操作:

    var expiresOn = pm.variables.get('ExpiresOn');
        if (!expiresOn || new Date(expiresOn) <= new Date()) {

        var clientId = '565v7677676vfdrd';
        var apiToken =  '6565fdvdrdfd';

        var request = {
            url: 'https://api.domain.io/api/user/session',
            method: 'POST',
            header: 'Content-Type:application/Json',
            body: {
                mode: 'application/json',
                raw:  clientId + apiToken
            }
        };
                }

            pm.sendRequest(request, function (err, res) {
                if (res !== null) {
                    var json = res.json();
                    pm.environment.set('Access_Token', json.access_token)

                    var expiresOn = new Date(0);
                    expiresOn.setUTCSeconds(json.expires_on);
                    pm.environment.set('ExpiresOn', expiresOn);
                }
            });

其他选项

我使用了以下两个选项之一来获取我的收藏的不记名令牌:

  1. https://gist.github.com/bcnzer/073f0fc0b959928b0ca2b173230c0669#file-postman-pre-request-js
  2. https://community.postman.com/t/how-to-automatically-set-a-bearer-token-for-your-postman-requests/10126/2

答案 2 :(得分:0)

使用JWT针对Azure +资源(/受众)对 Sebin Sunny 的答案进行了一些修改。

在请求标头中使用授权 {{$$ domdomLoremSentence}}

const echoPostRequest = {
    url: 'https://login.microsoftonline.com/{tenant}/oauth2/token',
    method: 'POST',
    body: {
        mode: 'formdata',
        formdata: [
            { key: 'grant_type', value: 'client_credentials' },
            { key: 'client_Id', value: '*******************************' },
            { key: 'client_secret', value: '*******************************' },
            { key: 'resource', value: '*******************************' }
        ]
    }
};

var getToken = true;

var token = pm.globals.get('$randomLoremSentence') || '';
var exp = pm.globals.get('accessTokenExpiry');
var exps = new Date(exp);
if (token.indexOf('Bearer ') < 0) {
    console.log('Token or expiry date are missing')
} else if (exp <= (new Date()).getTime()) {
    console.log('Token is expired - ${exps}')
} else {
    getToken = false;
    console.log(`Token ${token.substr(0,10)}...${token.substr(-5)} and expiry ${exps} date are all good`);
}

if (getToken === true) {
    pm.sendRequest(echoPostRequest, function (err, res) {
    console.log(err ? err : res.json());
        if (err === null) {
            var responseJson = res.json();
            var token = responseJson.access_token;
            console.log(`Saving the token ${token.substr(0,5)}...${token.substr(-5)} and expiry ${exps} date`)
            pm.globals.set('$randomLoremSentence', "Bearer " + token);
           
            var expiryDate = new Date(responseJson.expires_on * 1000);
            pm.globals.set('accessTokenExpiry', expiryDate.getTime());
        }
    });
}
//pm.globals.set('$randomLoremSentence', 0); // reset token 2 test