如何在Postman OAuth 2.0获取令牌流程中添加Origin请求头?
解决Postman中Azure AD OAuth2.0授权码+PKCE流程的Origin头缺失问题
问题背景
在OAuth 2.0授权码+PKCE授权流程中,Azure AD对单页应用(SPA)类型的客户端有特殊要求:向/token端点发起的令牌兑换请求必须携带Origin请求头,缺少该头会触发错误:
Error: AADSTS9002327: Tokens issued for the 'Single-Page Application' client-type may only be redeemed via cross-origin requests
但Postman自带的「获取新访问令牌」流程不会自动添加这个Origin头,导致令牌请求失败。尝试给绑定令牌的请求添加头、使用「预请求脚本」均无效,需要找到能给这个后台执行的请求添加自定义头的方法。
可行解决方案
方法一:使用Postman Interceptor代理
通过Postman的Interceptor扩展来拦截并修改令牌请求:
- 安装Postman Interceptor浏览器扩展并启用
- 在Postman的「代理」设置中开启Interceptor功能
- 进入Interceptor的「请求头」配置页面,添加规则:当请求URL匹配Azure AD的
/token端点时,添加Origin请求头,值填写你的SPA域名(例如https://your-spa-domain.com)
方法二:手动构造令牌兑换请求
放弃Postman自带的OAuth流程,自行创建POST请求完成令牌兑换:
- 新建一个POST请求,目标URL为Azure AD的
/token端点(例如https://login.microsoftonline.com/{你的租户ID}/oauth2/v2.0/token) - 在请求头中添加
Content-Type: application/x-www-form-urlencoded和Origin: https://your-spa-domain.com - 在请求体的「urlencoded」中添加所有必要参数:
grant_type: authorization_codecode: 你获取到的授权码code_verifier: 对应PKCE流程的code_verifierclient_id: 你的SPA客户端IDredirect_uri: 你的SPA重定向URI
- 发送请求获取令牌后,可手动将令牌粘贴到需要的请求中,或保存到Postman环境变量复用
方法三:用Postman脚本自动获取令牌
利用Postman的脚本能力,在预请求脚本中直接调用/token端点并添加Origin头,将令牌存入环境变量:
pm.sendRequest({ url: 'https://login.microsoftonline.com/你的租户ID/oauth2/v2.0/token', method: 'POST', header: { 'Content-Type': 'application/x-www-form-urlencoded', 'Origin': 'https://your-spa-domain.com' }, body: { mode: 'urlencoded', urlencoded: [ {key: 'grant_type', value: 'authorization_code'}, {key: 'code', value: pm.variables.get('auth_code')}, {key: 'code_verifier', value: pm.variables.get('code_verifier')}, {key: 'client_id', value: '你的客户端ID'}, {key: 'redirect_uri', value: '你的重定向URI'} ] } }, function (err, res) { if (err) { console.error(err); } else { const tokenData = res.json(); pm.environment.set('access_token', tokenData.access_token); pm.environment.set('refresh_token', tokenData.refresh_token); } });
注意:这种方法需要先获取授权码auth_code和对应的code_verifier,可通过手动完成授权码流程第一步获取,或进一步编写脚本自动完成授权码获取。
内容的提问来源于stack exchange,提问作者Juriy
相关产品推荐
相关产品推荐

