授权承载令牌的Postman预请求脚本

euoag5mw  于 2023-11-18  发布在  Postman
关注(0)|答案(4)|浏览(194)

我试图使脚本生成我的身份验证承载令牌的集合.所以我不必每次传递令牌,我将继承认证从父.但我不知道我在脚本中的错误,我不能生成令牌,它给我错误

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);
            }
        });
    }

zdwk9cvp

zdwk9cvp1#

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());
        }
    });
}

上面的例子是一个Postman Pre-request脚本来获取access_token,以及token的过期时间。我认为这个例子可以帮助你解决这个问题。请检查Postman的控制台打开Postman控制台在Windows上按Ctrl+Alt+C(Mac上按Cmd + Alt+ C)
x1c 0d1x的数据

50few1ms

50few1ms2#

返回错误

当运行你的脚本时,我得到了以下错误:

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
ssgvzors

ssgvzors3#

Sebin Sunny的答案经过了修改,使用JWT对Azure +资源(/audience)进行了测试。

在请求头中使用**Authorization*{{$randomLoremSentence}}*

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

字符串

eoigrqb6

eoigrqb64#

我在寻找别的东西的时候遇到了这个问题。
这是预请求脚本的另一个示例,它处理令牌过期,还包含一些测试,以便在出现任何错误时更容易进行故障排除。
您必须将主体更改为适当的授予类型。

let currentDateTime = Date.now();
let tokenExpiry = pm.environment.get("bearerTokenExpiresOn")
// console.log("currentDateTime: " + currentDateTime);
// console.log("tokenExpiry: " + tokenExpiry);
if (!pm.environment.get("bearerToken") || currentDateTime > tokenExpiry) {
    pm.test("Pre-request check for Environment Variables", function () {
        let vars = ['clientId', 'clientSecret', 'tenantId', 'username', 'password', 'scope'];
        vars.forEach(function (item) {
            // console.log(item);
            pm.expect(pm.environment.get(item), item + " variable not set").to.not.be.undefined;
            pm.expect(pm.environment.get(item), item + " variable not set").to.not.be.empty;
        });
        pm.sendRequest({
            url: 'https://login.microsoftonline.com/' + pm.environment.get("tenantId") + '/oauth2/v2.0/token',
            method: 'POST',
            header: 'Content-Type: application/x-www-form-urlencoded',
            body: {
                mode: 'urlencoded',
                urlencoded: [
                    { key: "client_id", value: pm.environment.get("clientId"), disabled: false },
                    { key: "scope", value: pm.environment.get("scope"), disabled: false },
                    { key: "username", value: pm.environment.get("username"), disabled: false },
                    { key: "password", value: pm.environment.get("password"), disabled: false },
                    { key: "client_secret", value: pm.environment.get("clientSecret"), disabled: false },
                    { key: "grant_type", value: "password", disabled: false },
                ]
            }
        }, function (err, res) {
            if (err) {
                console.log(err);
            } else {
                pm.test("Pre-request Microsoft login Status code is 200", () => {
                    pm.expect(res).to.have.status(200);
                    let resJson = res.json();
                    // console.log(resJson);
                    pm.environment.set("bearerToken", resJson.id_token);
                    pm.environment.set("bearerTokenExpiresOn", Date.now() + resJson.expires_in * 1000);
                    // console.log("bearerTokenExpiresOn: " + pm.environment.get("bearerTokenExpiresOn"));
                });
            }
        });
    });
};

字符串

相关问题