如何修复Postman获取新访问令牌的错误?

问题描述 投票:0回答:1

配置:

Auth type: Oauth 2.0
Client Id: provided
Client Secret: provided
grant_type: client_credentials

我试图通过单击“获取新访问令牌”按钮在 Postman 中检索访问令牌,但它在控制台中抛出错误,仅显示:

Error: []

即使请求成功(如控制台中所示),它也会抛出错误。请求正文包含以下内容:

{"tokenData":{"access_token":"access-token-here","token_type":"Bearer","expires_in":31556926},"errors":[],"success":true}

我的假设是邮递员默认期望这种格式:

{"access_token":"access-token-here","token_type":"Bearer","expires_in":31556926}
postman
1个回答
0
投票

邮递员授权助手期望这些密钥位于平面对象中。

这符合 OAuth 2.0 标准。

https://datatracker.ietf.org/doc/html/rfc6749#section-5.1

参数包含在HTTP响应的实体主体中 使用[RFC4627]定义的“application/json”媒体类型。 这 参数被序列化为 JavaScript 对象表示法 (JSON) 通过在最高结构级别添加每个参数来构建结构。 参数名称和字符串值作为 JSON 字符串包含在内。 数值以 JSON 数字形式包含在内。 的顺序 参数并不重要并且可以变化。

您可以设置预请求脚本来处理非标准响应。

以下是向 Microsoft 进行身份验证的示例,您可以将其用作基准。

let moment = require('moment');
let currentDateTime = moment(new Date()).format("YYYYMMDDHHmmss");
let tokenExpiry = moment(pm.environment.get("bearerTokenExpiresOn")).format("YYYYMMDDHHmmss");

// console.log("currentDateTime: " + currentDateTime);
// console.log("tokenExpiry: " + tokenExpiry);
// console.log(pm.environment.get("bearerToken"));


if (!pm.environment.get("bearerToken") || currentDateTime > tokenExpiry) {
    pm.test("Pre-request check for Environment Variables", function () {
        let vars = ['client_id', 'scope', 'tenant_id', 'client_secret', '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("tenant_id") + '/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("client_id"), disabled: false },
                    { key: "scope", value: pm.environment.get("scope"), disabled: false },
                    { key: "client_secret", value: pm.environment.get("client_secret"), disabled: false },
                    { key: "grant_type", value: "client_credentials", 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);
                    let token = resJson.access_token;
                    // console.log(token);

                    function parseJwt(token) {
                        var base64Url = token.split('.')[1];
                        var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
                        var jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
                            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
                        }).join(''));

                        return JSON.parse(jsonPayload);
                    }

                    let decoded = parseJwt(token);
                    // console.log(decoded);
                    let expiryDate = new Date(decoded.exp * 1000);
                    // console.log(expiryDate);

                    pm.environment.set("bearerToken", token);
                    pm.environment.set("bearerTokenExpiresOn", expiryDate);
                    // console.log("bearerTokenExpiresOn: " + pm.environment.get("bearerTokenExpiresOn"));
                });
            }
        });
    });
};

此示例正在解析令牌,因为 API 问题未返回到期日期。

如果现有令牌已过期,代码只会获取新令牌。 请密切注意数据格式,因为并非所有 API 都使用相同的格式。 (甚至 Microsoft API 根据正在验证的服务返回不同的格式)。

最后要检查的是身份验证 API 是否有任何用于控制输出的选项。 有时,您可以发送带有请求的查询参数,以配置 Postman 在授权帮助程序中的高级选项中支持的响应外观。

© www.soinside.com 2019 - 2024. All rights reserved.