我正在使用AWS认知托管的UI作为我的注册和登录。没有应用程序客户端机密定义。
我正在尝试从浏览器javascript代码到/OAuth2/令牌端点进行API调用,以便使用ID令牌交换autohorization_token。
问题是,当我通过邮递员打电话时,失眠症是很好的。然而,当我通过浏览器的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 );这是我得到的回应:

我用获取尝试了相同的请求,结果是一样的。
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();当我检查browser developer工具时,我意识到了一件事:当我使用内容类型=application/x-www-form-urlencoded对端点进行其他POST调用时,它显示了添加到URL中的查询参数,如下所示,但是对于我的调用,params不是作为URL的一部分编码的。我不知道这个问题是否与此有关。

知道我怎么能用客户端的javascript打这个电话吗?
发布于 2021-10-19 18:58:12
看起来浏览器使用的是redirect_url,这是错误的,邮递员使用的是redirect_uri,这是正确的。另外,您应该使用PKCE来使消息更安全--请参阅我的博客帖子的步骤4和步骤8,以了解这看起来如何。
还请注意,在OAuth中,如果提供了未识别的客户端ID或重定向URI,则通常不返回错误详细信息或返回应用程序。如果这两者都是正确的,则应该在响应有效负载中接收标准的OAuth、error和error_description字段。
https://stackoverflow.com/questions/69622675
复制相似问题