在使用谷歌登录AWS Cognito托管UI时出现CORS问题



所以我在AWS Cognito上设置了通过Google登录。对于应用程序客户端,我使用代码授予。但问题是,当我从?code=1234abdce#$%传递生成的代码到以下格式的url:

let root_url = `https://<our_apps_domain>.auth.us-east-1.amazoncognito.com/oauth2/token`
let content_type = "Content-Type='application/x-www-form-urlencoded'&"
let grand_type ='grant_type=authorization_code&'
let client_id='client_id='+process.env.GOOGLE_APP_CLIENT_ID+'&'
let code_grant='code='+code+"&"
let redirect_uri='redirect_uri='+process.env.FRONTEND_URL+'/home'
let code_grant_url=root_url+content_type+grand_type+client_id+code_grant+redirect_uri
fetch(code_grant_url,{
method:'POST',
headers:{
'Access-Control-Allow-Origin':process.env.FRONTEND_URL
}
}).then((res) =>
!res.ok ? res.json().then((e) => Promise.reject(e)) : res.json()
)

我得到一个CORS错误:来自原点'http://localhost:3000'已被CORS策略阻止:对预飞行请求的响应不通过访问控制检查:请求的资源上不存在' access - control - allow - origin '标头。如果一个不透明的响应满足你的需要,设置请求的模式为'no-cors'来获取CORS禁用的资源。这里有什么问题?

您必须将Content-Type标头设置为application/x-www-form-urlencoded,详细说明如下。

不是查询字符串参数。实际上,查询字符串中不需要传递任何参数。你应该使用urlencoded体,所以只是采取你的查询字符串,并将其作为请求体传递。或者更好的是,URLSearchParams构造函数来改进您的代码。

fetch('https://<our_apps_domain>.auth.us-east-1.amazoncognito.com/oauth2/token',{
method:'POST',
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
grant_type: 'authorization_code',
client_id: process.env.COGNITO_CLIENT_ID,
redirect_uri: `${process.env.FRONTEND_URL}/home`,
code,
code_verifier
})
})

此外,由于您使用的是公共客户端(浏览器),因此必须使用PKCE授予的授权代码。

最新更新