通过curl命令发送POST请求

时间:2015-09-24 08:47:44

标签: java spring rest

我有通过curl命令发送POST请求的问题。

     @RequestMapping(value = "/abc/def/{parameter}/enum", method = RequestMethod.POST)
     public ResponseEntity<classA> function(@PathVariable(value = "parameter") int parameter, @RequestBody String parameter2) {
           a = list.get(parameter);
           a.setParameter(enumA.getValue(parameter2));
           ResponseEntity<classA> response = new ResponseEntity<>(a, HttpStatus.OK);
          return response;
     }

然后我想通过curl命令发送POST:

curl -H "Content-Type: application/json" -X POST -d '{"parameter2" : "enum"}' https://user:password@localhost:port/abc/def/1/enum -k

我得到回应:

{"timestamp":123456789,"status":403,"error":"Forbidden","message":"Expected CSRF token not found. Has your session expired?","path":"/abc/def/1/enum/"}

想法?

1 个答案:

答案 0 :(得分:1)

问题是:

Expected CSRF token not found.

您的应用程序(我可以看到Spring MVC)启用了CSRF保护,因此您需要发送&#34; _csrf&#34; param与帖子。 更多信息:
http://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html
https://spring.io/blog/2013/08/21/spring-security-3-2-0-rc1-highlights-csrf-protection/

CSRF令牌值随用户会话而变化,如果您想查看此csrf令牌,您可以使用Web浏览器访问您的应用程序并查看页面的HTML代码,在表单标签中您将看到如下内容:

<input type="hidden"
    name= _csrf
    value= 964f8675-a57a-4f85-b196-976d71ffef96 />

所以你需要在你的POST中发送这个参数。

curl -H "Content-Type: application/json" -X POST -d '{"parameter2" : "enum","_csrf":"964f8675-a57a-4f85-b196-976d71ffef96"}' -u username:password https://localhost:port/abc/def/1/enum

关注!:正如我所说,此令牌会随着用户会话而改变,因此您将无法始终使用相同的令牌。

相关问题