【发布时间】:2021-12-05 21:34:10
【问题描述】:
我正在使用 AWS Cognito 托管的 UI 进行注册和登录。没有定义应用客户端密码。
我正在尝试从浏览器 javascript 代码向/oauth2/token 端点进行 API 调用,以便将 autohorization_token 与 ID 令牌交换。
问题是,当我通过 Postman 拨打电话时,Insomnia 工作正常。 但是,当我通过 浏览器中的 javascript 拨打同样的电话时,它会失败并显示400 响应类型,我无法了解原因。
这是成功的失眠电话;
但是,当我通过 javascript 进行相同的调用时,它会失败。 我已经使用了 fetch 和 XMLHttpRequest 并且结果相同。
const XHR = new XMLHttpRequest();
let urlEncodedData = "",
urlEncodedDataPairs = [],
name;
urlEncodedDataPairs.push( encodeURIComponent( 'grant_type' ) + '=' + encodeURIComponent( 'authorization_code' ) );
urlEncodedDataPairs.push( encodeURIComponent( 'code' ) + '=' + encodeURIComponent( code ) );
urlEncodedDataPairs.push( encodeURIComponent( 'client_id' ) + '=' + encodeURIComponent( 'xxxxx' ) );
urlEncodedDataPairs.push( encodeURIComponent( 'redirect_url' ) + '=' + encodeURIComponent( 'https://www.xxx.me/xxx' ) );
XHR.addEventListener( 'load', function(event) {
alert( 'Yeah! Data sent and response loaded.' );
} );
// Define what happens in case of error
XHR.addEventListener( 'error', function(event) {
alert( 'Oops! Something went wrong.' );
});
// Set up our request
XHR.open( 'POST', 'https://xxx.auth.us-west-2.amazoncognito.com/oauth2/token' );
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
// Finally, send our data.
XHR.send( urlEncodedData );
这是我得到的回复:
我用fetch尝试了同样的请求,结果是一样的。
let tokenRequest = new Request(tokenURL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Origin' : 'https://www.xxx.me'
},
body: new URLSearchParams({
'grant_type': 'authorization_code',
'code': code,
'client_id': 'xxx',
'redirect_url': 'https://www.xxx.me/xxx'
}).toString()
});
let response = await fetch(tokenRequest);
let data = await response.json();
当我检查浏览器开发人员工具以查看对内容类型 = application/x-www-form-urlencoded 的身份验证端点进行的其他 POST 调用时,我意识到了一件事,它显示了添加到 URL 的查询参数,如下所示,但是,对于我的电话,参数不编码为 URL 的一部分。我不确定问题是否与此有关。
知道如何使用客户端 javascript 进行此调用吗?
【问题讨论】:
-
我认为您可以使用 Postman 的 Fetch 或 jQuery 检查 Javascript 的确切格式 - 工作案例的代码片段并将其用作模板来重新构建您的代码。
-
你确定
code在你的请求被发送时被定义了吗? -
@AndrewGillis 是的,我发送代码。
标签: javascript oauth-2.0 aws-api-gateway amazon-cognito