AWS Cognito授权码模式请求Axios报405 Method Not Allowed求助
解决AWS Cognito授权码流程405 Method Not Allowed错误
问题描述
使用AWS Cognito托管UI搭配Express后端,通过授权码授予流程获取令牌时,持续返回405: Method Not Allowed错误。已确认凭证、区域正确,能从URL中获取code,Base64编码的授权信息无误,尝试过重定向URL带/和不带/的形式,调整凭证在Header和Body中的位置,均未解决问题。
Cognito设置截图:
原代码:
let code= req.query.code; if(code== undefined || code === null) { next(); return; } let encodedAuth ="Basic "+base64encode(process.env.COGNITO_APP_CLIENT+":"+process.env.COGNITO_APP_CLIENT_SECRET); await axios({ method: 'post', url: 'https://MYDOMAIN.auth.us-east-2.amazoncognito.com/oauth2/token', header: { Content_Type: "application/x-www-form-urlencoded", Authorization:encodedAuth}, data:{ grant_type:'authorization_code', code:code, client_id:process.env.COGNITO_APP_CLIENT, redirect_uri:'http://localhost:8080/' } }) .then(function(err,value){ console.log("Here!"); }) .catch(function(err,value){ console.log("Error while logging in!"); console.log(err); })
错误原因及修复步骤
1. Axios配置项拼写错误
原代码中header应为headers(复数形式),Content_Type应为Content-Type(短横线而非下划线),这会导致请求头未正确设置,Cognito无法识别请求格式从而返回405。2. 请求数据未做URL编码
Cognito的/oauth2/token端点要求请求体为application/x-www-form-urlencoded格式,而Axios默认会将data序列化为JSON,需要手动将数据转换为URL编码格式,可使用qs.stringify处理。3. Promise回调参数错误
.then()的第一个参数是成功响应对象,不是err;.catch()的第一个参数是错误对象,无需第二个参数value。4. 确保重定向URL完全匹配
需确认Cognito应用客户端配置中的重定向URL与代码中的redirect_uri完全一致(包括协议、端口、末尾的/),参考你提供的Cognito设置截图仔细核对。
修复后的代码示例
const qs = require('qs'); // 需先安装qs:npm install qs let code = req.query.code; if (code == undefined || code === null) { next(); return; } // Node.js中建议用Buffer.from替代自定义base64encode,避免编码问题 let encodedAuth = "Basic " + Buffer.from(`${process.env.COGNITO_APP_CLIENT}:${process.env.COGNITO_APP_CLIENT_SECRET}`).toString('base64'); try { const response = await axios({ method: 'post', url: 'https://MYDOMAIN.auth.us-east-2.amazoncognito.com/oauth2/token', headers: { "Content-Type": "application/x-www-form-urlencoded", Authorization: encodedAuth }, data: qs.stringify({ grant_type: 'authorization_code', code: code, client_id: process.env.COGNITO_APP_CLIENT, redirect_uri: 'http://localhost:8080/' // 确保与Cognito配置完全一致 }) }); console.log("令牌获取成功:", response.data); } catch (err) { console.log("登录时出错!"); console.log(err.response?.data || err.message); }
额外检查项
- 确认Cognito应用客户端已开启
Authorization code grant流程(从截图看已勾选,可再次确认)。 - 检查Express路由是否正确接收GET请求(授权码通过URL查询参数传递,路由应为GET方法)。
内容的提问来源于stack exchange,提问作者New2WebDev
相关产品推荐
相关产品推荐

