我正在使用 AWS Cognito 和 Google 注册与 React。我到达了身份验证代码出现在redirected_uri 顶部的步骤。现在,我正在尝试向
发送帖子请求https://<my_domain>.amazoncognito.com/oauth2/token
获取访问令牌和 ID 令牌。
代码出现在搜索栏上,如下所示:
http://localhost:3000/?code=e3090fba-d39c-4c8d-aaf9-4e82ebafcc70&state=BBCxKTIPx4QLwD17kOAhl0OyKo3f7g7O
我在主页中使用了以下代码从URI中获取代码,然后将post请求发送到上面的uri:
useEffect(() => {
const exchangeCodeForTokens = async () => {
try {
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.has('code')) {
const dcode = urlParams.get('code');
const code = String(dcode)
console.log(code)
const tokenEndpoint = 'https://<my-domain>.amazoncognito.com/oauth2/token';
const clientId = <my-cognito-client-id>;
const redirectUri = 'http://localhost:3000';
const bodyParams = new URLSearchParams();
bodyParams.append('grant_type', 'authorization_code');
bodyParams.append('client_id', clientId);
bodyParams.append('code', code);
bodyParams.append('redirect_uri', redirectUri);
const response = await fetch(tokenEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: bodyParams.toString(),
});
console.log(response)
const data = await response.json();
const accessToken = data.access_token;
const idToken = data.id_token;
const refreshToken = data.refresh_token;
console.log(data,accessToken, idToken, refreshToken)
console.log('Token exchange successful');
}
} catch (error) {
console.error(error);
}
};
exchangeCodeForTokens();
}, []);
我收到以下错误:
AWS-Cognito 中的 OAuth 授予类型在授权代码授予中设置
我的 AWS-Amplify 配置:
Amplify.configure({
Auth: {
region: '*******',
userPoolId: '***************',
userPoolWebClientId: '**************',
oauth : {
domain: '<domain-name>.amazoncognito.com',
redirectSignIn: 'http://localhost:3000',
redirectSignOut: 'http://localhost:3000',
scope : ['email', 'openid', 'profile', 'phone', 'aws.cognito.signin.user.admin'],
responseType: 'code'
}
}
})
我遇到了同样的错误,只能通过使用使用客户端密钥创建的 Cognito 应用程序客户端来解决它。来自 AWS Token 端点文档的指针此处
在机器对机器模型中,您的应用程序将客户端密钥发送到 您的令牌端点以换取访问令牌。
在同一文档中,他们没有给出在没有客户端密钥的情况下使用令牌端点的示例。
此外,当请求缺少必需的参数、包含不受支持的参数值(不支持的_grant_type 除外)或格式错误时,通常会出现您收到的错误消息“invalid_request”。
工作代码片段(我使用 axios 进行 API 调用)
const params = {
grant_type: 'authorization_code',
client_id: global.clientId,
redirect_uri: global.redirectUri,
code: googleAuthID
};
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
auth: {
username: global.clientId,
password: global.clientSecret
}
};
try {
const response = await axios.post(
`https://${global.domainPrefix}.auth.us-east-1.amazoncognito.com/oauth2/token`,
querystring.stringify(params),
config
);
return {
statusCode: 200,
message: 'User successfully Logged In via Google',
accessToken: response.data.access_token,
token: response.data.id_token,
expiresIn: response.data.expires_in
};