Angular调用AWS Cognito Token接口返回405 Method Not Allowed问题
AWS Cognito /oauth2/token接口405 Method Not Allowed问题排查
问题描述
用户通过SSO登录后重定向到授权页面获取authorization_code,使用Angular调用AWS Cognito的/oauth2/token接口完成授权时,无论将参数放在params还是body中,均返回405 Method Not Allowed错误。相关代码如下:
let headers = new HttpHeaders(); let auth = btoa(<clientId> + ':<client secret'); headers.set('Content-Type', 'application/x-www-form-urlencoded'); headers.set('Authorization', `Basic ${auth}`); headers.set('Accept', 'application/json'); this.http.post( 'https://<cognito domain>/oauth2/token', null, { headers, params: new HttpParams() .set('grant_type', 'authorization_code') .set('code', <code>) .set('redirect_uri', <redirect url>) .set('client_id', <clientId>) } )
排查与解决步骤
修正请求参数位置与格式:Cognito的
/oauth2/token接口要求POST请求的所有参数必须放在请求体中(格式为application/x-www-form-urlencoded),不能放在URL参数里。同时不要同时传递Authorization头和client_id参数,二选一即可。
修正后的代码示例:const clientId = '<你的clientId>'; const clientSecret = '<你的clientSecret>'; const auth = btoa(`${clientId}:${clientSecret}`); const headers = new HttpHeaders() .set('Content-Type', 'application/x-www-form-urlencoded') .set('Authorization', `Basic ${auth}`) .set('Accept', 'application/json'); // 构造请求体参数 const body = new HttpParams() .set('grant_type', 'authorization_code') .set('code', '<获取到的authorization_code>') .set('redirect_uri', '<你的重定向URI>'); this.http.post( 'https://<你的cognito domain>/oauth2/token', body, { headers } ).subscribe( response => console.log('授权成功:', response), error => console.error('授权失败:', error) );检查Cognito客户端配置:
- 确认用户池客户端的「允许的OAuth流」包含
Authorization code grant; - 确认代码中
redirect_uri与客户端配置的重定向URI完全一致(包括协议、域名、路径,无任何差异); - 如果客户端设置了密钥,必须使用Basic Auth头;未设置密钥则无需传Auth头,改为在请求体中传入
client_id。
- 确认用户池客户端的「允许的OAuth流」包含
校验请求头正确性:
Content-Type必须严格为application/x-www-form-urlencoded;- 确保
btoa编码的clientId:clientSecret格式正确,不要包含多余转义字符或符号。
检查CORS配置:如果是浏览器端发起请求,需在Cognito用户池的「App客户端设置」中,将前端域名添加到「允许的源」列表,同时确保允许POST方法和所需请求头。
内容的提问来源于stack exchange,提问作者dcp3450
相关产品推荐
相关产品推荐

