You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic Angular中向第二个SAP API传递csrf-token避免验证失败

SAP API CSRF验证失败与跨域问题解决方案

一、CSRF令牌403失败的修复步骤

SAP的CSRF令牌是和会话Cookie绑定的,只拿token不带对应Cookie,后端必然验证失败。你需要在两个请求里都开启withCredentials:

  1. 修改第一个获取token的请求,添加withCredentials: true,让浏览器保存并携带Cookie:
fetchIsAliveSetDetails(token,order){
    console.log("INSIDE fetchIsAliveSetDetails");
    
    const httpOptions: Object = {
        headers: new HttpHeaders({
            'x-csrf-token': 'fetch',
            'Authorization':'Bearer '+token
            // 删掉Access-Control-Allow-Headers,这是后端响应头,前端加了没用
        }),
        observe: 'response',
        withCredentials: true // 新增这个配置
    };
    this.http.get<any>(this.isAliveSetURL, httpOptions).pipe(first()).subscribe(
        (res)  => {
            var csrfToken = res.headers.get("x-csrf-token");
            this.sendOrderSet(order,csrfToken,this.oAuthToken);
        }, (err) => {
            console.log(JSON.stringify(err));
            return "error";
        }
    );
}
  1. 第二个POST请求同样开启withCredentials: true:
sendOrderSet(order,xToken,token){
    const httpOptions: Object = {
        headers: new HttpHeaders({
            'x-csrf-token':xToken,
            'Authorization':'Bearer '+token,
            'content-type':'application/json'
        }),
        withCredentials: true // 开启这个
    };
    this.http.post(this.SAP_API_URL + "/SalesOrderSet",order,httpOptions).subscribe(
        (res)  => {
            console.log("salesOrder"+res);
            return "success ";
        }, (err) => {
            console.log("-- -- "+JSON.stringify(err));
            return "error";
        }
    );
}

二、Access-Control-Allow-Credentials的正确位置

Access-Control-Allow-Credentials: true是后端SAP API必须返回的响应头,前端不需要在请求里设置。同时后端还要满足两个条件:

  • Access-Control-Allow-Origin不能设为*,必须指定你的前端具体域名(比如https://your-frontend.com),带凭证的跨域请求不允许通配符origin
  • 响应头里必须包含Access-Control-Allow-Credentials: true

额外提醒

  • 前端请求里的Access-Control-Allow-Headers属于无效配置,直接删掉即可,这个是后端用来告知浏览器允许哪些请求头的响应头。
  • 确认获取token和提交订单的两个API请求,域名、端口完全一致,避免跨域导致Cookie无法携带。

内容的提问来源于stack exchange,提问作者Rajiv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 02:20:36