douchanxiu5636 2018-10-07 10:29
浏览 409
已采纳

发布操作失败,并显示“ CSRF令牌验证失败”错误

I am trying POST operation on SAP Hybris C4C entity.

I came across many blogs where it was mentioned that we need to send X-CSRF-Token during POST which can first be retrieved using GET operation.

I was successfully able to do that using Postman. as Postman stores cookie not causing to CSRF token validation failure.

But, I actually want to call this using golang. And I was getting everytime error as "CSRF token validation failed". Then after going through many blogs I found we not only have to set X-CSRF-Token but also Cookie so that HTTP POST is not treated as new session. otherwise the csrf token we sent does not match with current session causing error.

Even after following above two leads, I am still getting error. Below is the code snippet, I am not sure what else is missing.

Code snippet:

auth := "******:*****"
basicAuth := base64.StdEncoding.EncodeToString([]byte(auth))

geturl := "https://******.crm.ondemand.com/sap/c4c/odata/v1/c4codataapi"
req, _ := http.NewRequest("GET", geturl, nil)
req.Header.Set("Authorization", "Basic "+basicAuth)
req.Header.Set("X-Csrf-Token", "Fetch")
cli := &http.Client{}
res, _ := cli.Do(req)

inputMap := make(map[string]interface{})
inputMap["PriorityCodeText"] = "Normal"
inputJSON, _ := json.Marshal(inputMap)

url := "https://*******.crm.ondemand.com/sap/c4c/odata/v1/c4codataapi/OpportunityCollection"
request, _ := http.NewRequest("POST", url, bytes.NewBuffer(inputJSON))
request.Header.Set("Authorization", "Basic "+basicAuth)
request.Header.Set("X-Csrf-Token", res.Header.Get("X-Csrf-Token"))
request.Header.Set("Cookie", res.Header.Get("Set-Cookie"))
request.Header.Set("X-Requested-With", "XMLHttpRequest")
request.Header.Set("Content-Type", "application/atomsvc+xml")
request.Header.Set("DataServiceVersion", "2.0")
//request.Header.Set("Accept", "application/atom+xml")
client := &http.Client{}
resp, _ := client.Do(request)
fmt.Printf("Response status code is: %d", resp.StatusCode)
jsonResponseData, _ := ioutil.ReadAll(resp.Body)
fmt.Printf("Response is: %s", jsonResponseData)
  • 写回答

1条回答 默认 最新

  • douyou7878 2018-10-07 17:34
    关注

    It worked! As mentioned by @gp, I had to copy all cookies instead of just setting header. I did below change in code snippet

    //request.Header.Set("Cookie", res.Header.Get("Set-Cookie"))
    for i := 0; i < len(res.Cookies()); i++ {
        request.AddCookie(res.Cookies()[i])
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧