【问题标题】:NestJS - Axios Oath2 get third party access tokenNestJS - Axios Oath2 获取第三方访问令牌
【发布时间】:2020-07-08 02:08:23
【问题描述】:

我是 NestJS 的新手,我编写了以下代码以从第三方获取访问令牌,但 API 响应 data: error: 'invalid_request', error_description: 'Missing Mandatory Parameters'} 可能是我缺少标题或其他内容。

我正在使用以下代码:

async getEquifaxToken() {
    const token_params = {
        grant_type: 'client_credentials',
        client_id: 0000,
        client_secret: 0000,
        scope: 'https://api.equifax.com/business/consumer-credit/v1',
    };

    try {
        const response = await axios.post(
            environment.equifax_api_url + 'v2/oauth/token',
            querystring.stringify(token_params)
        );
        console.log('--response--', response.data);
    } catch (error) {
        console.error(error);
    }
    console.log('--before after--');
}

我从 POSTMAN 身份验证弹出窗口获得了访问令牌。

【问题讨论】:

  • 当您在 Postman 中发出该请求时,很可能会发送我在您的 axios 请求中看不到的“授权”标头。我可以看到 Postman 正在使用基本身份验证,它只是连接用户名 + 密码,然后进行 base64 编码,因此您需要执行相同操作并将其添加为请求的标头。我建议在 axios 中使用“auth”选项:masteringjs.io/tutorials/axios/basic_auth
  • @nerdybeast 它与授权参数无关,我已经在邮递员中取消了授权标头参数。

标签: oauth-2.0 nestjs typeorm


【解决方案1】:

错误是 client_id 和 client_secret 在 token_params 中没有用,所以只需添加 btoa 功能在nestJS 上不可用,您必须安装 btoa https://www.npmjs.com/package/btoa,然后在 headers 参数中包含 client_id 和 client_secret。

const client_id = 0000;
const client_secret = 0000;

const token_headers = {
  Authorization:
    'Basic ' +
    btoa(
      client_id +
        ':' +
        client_secret
    ),
};


async getEquifaxToken() {
const token_params = {
    grant_type: 'client_credentials',
    client_id: client_id,
    client_secret: client_secret,
    scope: 'https://api.equifax.com/business/consumer-credit/v1',
};

try {
    const response = await axios.post(
        environment.equifax_api_url + 'v2/oauth/token',
        querystring.stringify(token_params),
        {headers:token_headers}
    );
    console.log('--response--', response.data);
    //Here I got token successfully.
} catch (error) {
    console.error(error);
}

}

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 1970-01-01
    相关资源
    最近更新 更多