Angular中请求OAuth2.0访问令牌遇CORS及403错误求助
问题解决思路及修正代码
核心错误点分析
- 请求参数位置错误:OAuth2的
grant_type、scope等参数应放在请求体(采用x-www-form-urlencoded格式),而非请求头中。 - 客户端认证方式错误:你选择的Basic Auth方式,需要将
client_id:client_secret做Base64编码后放在Authorization头里,不能直接把client_id和secret写在headers中。 - 参数值错误:
grant_type的正确值是client_credentials,不是Client Credentials;token_name这类非标准OAuth2字段属于冗余配置,可删除。 - CORS问题:浏览器跨域限制导致403,需后端配置允许你的前端域名跨域,或通过Angular代理转发请求绕过限制。
修正后的Angular代码示例
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; // 组件类内部方法 getOAuthToken() { const clientId = '你的client_id'; const clientSecret = '你的client_secret'; // 生成Basic Auth的Authorization头 const authHeader = 'Basic ' + btoa(`${clientId}:${clientSecret}`); // 构造请求体参数 const body = new HttpParams() .set('grant_type', 'client_credentials') .set('scope', 'extended'); this.http.post( 'https://~~~/authorizationserver/oauth/token', body.toString(), { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': authHeader }) } ).subscribe( (response) => { console.log(response); }, (error) => { this.error = error.message; console.log(error); } ); }
CORS问题的临时解决方式(后端未配置跨域时)
通过Angular代理绕过浏览器跨域限制:
- 项目根目录创建
proxy.conf.json文件:
{ "/authorizationserver": { "target": "https://你的SAP域名", "secure": true, "changeOrigin": true } }
- 修改
angular.json中serve配置,添加代理引用:
"serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "proxyConfig": "proxy.conf.json" } }
- 将请求URL改为相对路径:
'/authorizationserver/oauth/token'
内容的提问来源于stack exchange,提问作者Claudio Godoy
相关产品推荐
相关产品推荐

