0

我正在尝试 AWS Cognito OAuth 2.0 客户端凭证流来获取访问令牌,我的代码如下,我尝试在邮递员上运行它并且它有效,我生成了代码以查看请求的结构,复制相同节点 HTTPS 的东西,这样我就可以在 lambda 函数中编写它,但是它不起作用,因为我不断收到连接被拒绝错误

"use strict";
const https = require("https");
const accessToken = null;

//the client credentials and client secret
const client_id = "xxxxxxx";
const client_secret = "xxxxxxxx";

const secretAndID = `${client_id}:${client_secret}`;
let bufferObj = Buffer.from(secretAndID, "utf-8");
let base64string = bufferObj.toString("base64");
console.log("base 64 string", base64string);

var accessOptions = {
  method: "POST",
  url: "https://xxxxxxx-dev.auth.eu-west-2.amazoncognito.com/oauth2/token",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    Authorization: `Basic ${base64string}`,
  },
};

//the accessToken generator runner
const accessTokenPayload = {
  grant_type: "client_credentials",
  scope: "",
  client_id: 'xxxxxx'
};

exports.handler = (event, context, callback) => {
const aToken = https.request(accessOptions, (res) => {
  let body = "";
  console.log("access token generator status:", res.statusCode);
  console.log("access token generator Response:", res);
  console.log("Headers:", JSON.stringify(res.headers));
  res.setEncoding("utf8");
  res.on("data", (chunk) => (body += chunk));
  res.on("end", () => {
    console.log("Successfully processed HTTPS response");
    body = JSON.parse(body);
    console.log("The access token generator body", body);
    callback(null, event);
  });
});

aToken.on("error", callback);
aToken.write(JSON.stringify(accessTokenPayload));
aToken.end();
}

我总是收到这个错误message: "PreSignUp failed with error connect ECONNREFUSED 127.0.0.1:443."

4

1 回答 1

0

所以我已经能够解决我的问题了,显然,HTTPS的使用要求你在它可以工作之前分解这种形式的端口,主机名和路径的URL

所以我在这里将其转换为

var accessOptions = {
  method: "POST",
  url: "https://xxxxxxx-dev.auth.eu-west-2.amazoncognito.com/oauth2/token",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    Authorization: `Basic ${base64string}`,
  },
};

我将上面的代码转换为

var accessOptions = {
  method: "POST",
  port: 443,
  hostname: "xxxasdax.amazoncognito.com",
  path: '/oauth2/token',
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    "Authorization": `Basic ${process.env.base64String}`,
  },
};

现在这解决了连接被拒绝的问题。

我必须做的另一件事是对我发送的数据进行编码URI,而不是发送 a JSON.stringify(payload),我必须执行以下操作

const bodyData = `${encodeURI('grant_type')}=${encodeURI(data.grant_type)}&${encodeURI('scope')}=${encodeURI(data.scope)}`;

这是我将我的有效负载转换为查询字符串,因为接受的内容类型是 "Content-Type": "application/x-www-form-urlencoded",

于 2021-01-17T16:04:43.710 回答