使用Authorization Code Grant调用AWS Cognito Token端点返回invalid_request错误
我通过Authorization Code Grant模式创建Cognito用户对象,已从重定向URL成功获取code和state,但调用/oauth2/token端点请求id、access、refresh令牌时,收到invalid_request响应,无法完成用户创建。
已确认信息
- 授权code获取成功,重定向URL示例:
http://localhost:3000/login-google?code=xxx-xxx-xxx-xxx-xxxxx&state=xxxxxxx
- 移除预令牌Lambda函数后问题仍存在,排除该函数影响
- 依赖版本:
"aws-amplify": "^5.0.17", "amazon-cognito-identity-js": "^6.1.2", "react": "^18.2.0"
调用/oauth2/token的代码实现
const AUTH_DOMAIN = 'https://xxx.auth.us-east-1.amazoncognito.com'; const grantType = 'authorization_code'; const clientId = 'xxx'; const clientSecret = 'xxxx', const redirectUri = `${window.location.origin}/login-google`; axios .post( `${AUTH_DOMAIN}/oauth2/token`, new URLSearchParams({ grant_type: grantType, code: code, state: state, client_id: clientId, redirect_uri: redirectUri }), { headers: { 'Content-Type': 'application/x-www-form-urlencoded', Authorization: getBase64EncodedCredential(clientId, clientSecret) } } ) .then((response) => { console.log(response.data); }) .catch((error) => { console.error(error); }); function getBase64EncodedCredential(cognitoAppId, cognitoAppSecret) { return 'Basic ' + btoaImplementation(cognitoAppId + ':' + cognitoAppSecret); } function btoaImplementation(str) { try { return btoa(str); } catch (err) { return Buffer.from(str).toString('base64'); //btoa is not implemented in node.js. } }
排查方向
- redirect_uri完全匹配:检查请求中的
redirect_uri与Cognito用户池应用客户端配置的“回调URL”是否完全一致,包括协议、域名、路径,不能有大小写差异或多余斜杠。 - code有效性:确认code未过期(Cognito授权code有效期5分钟)且未被使用过(每个code仅可使用一次)。
- 客户端认证方式:若应用客户端未生成客户端密钥(公开客户端),需移除请求头中的
AuthorizationBasic认证头,否则会触发无效请求。 - state参数一致性:确保当前请求的state与发起授权请求时生成的state完全一致,无篡改或丢失。
- 请求参数格式:验证
grant_type拼写是否为authorization_code,所有参数通过URLSearchParams正确序列化,无遗漏或格式错误。 - CORS配置:浏览器端请求需确认Cognito用户池的CORS设置允许当前域名发起POST请求到
/oauth2/token端点。
内容的提问来源于stack exchange,提问作者irfan
相关产品推荐
相关产品推荐

