出现"CSRF 令牌验证失败"错误导致后续操作无法完成
时间:2024-03-04
浏览:196
作者:佚名
偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《出现"CSRF 令牌验证失败"错误导致后续操作无法完成》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!
我正在尝试对 sap hybris c4c 实体进行 post 操作。
我看到很多博客都提到我们需要在 post 期间发送 x-csrf-token,可以首先使用 get 操作检索该令牌。
我使用 postman 成功地做到了这一点。因为 postman 存储 cookie 不会导致 csrf 令牌验证失败。
但是,我实际上想使用 golang 来调用它。我每次都会收到错误“csrf 令牌验证失败”。然后在浏览了很多博客之后,我发现我们不仅需要设置 x-csrf-token,还需要设置 cookie,这样 http post 就不会被视为新会话。否则,我们发送的 csrf 令牌与当前会话不匹配,从而导致错误。
即使遵循上述两条线索,我仍然收到错误。下面是代码片段,我不确定还缺少什么。
代码片段:
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)解决方案
成功了! 正如 @gp 所提到的,我必须复制所有 cookie,而不仅仅是设置标头。我在代码片段中做了以下更改
//request.Header.Set("Cookie", res.Header.Get("Set-Cookie"))
for i := 0; i < len(res.Cookies()); i++ {
request.AddCookie(res.Cookies()[i])
}我有时会在使用 tomcat 9 时遇到这个问题,就我而言,只需注销并重新登录即可解决问题。
java应用程序似乎使用了过期的cookie,但没有错误地将我重定向到注销页面。
理论要掌握,实操不能落!以上关于《出现"CSRF 令牌验证失败"错误导致后续操作无法完成》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
