jQuery POST在Spring MVC中给出403禁止的错误

问题描述:

我想使用$ .POST进行ajax调用.但是我收到403错误.但是GET可以正常工作.我的代码是:

I want to make a ajax call using $.POST. But I am getting 403 error. But GET works perfectly fine. My code is:

var url = "/xyz/abc/subscribe?name="+name;
$.post(url, function(data){
    alert(data);
});

控制器代码为:

@RequestMapping(value = "/xyz/abc/subscribe", method = RequestMethod.POST)
public @ResponseBody
    String subscribe(@RequestParam("name") String name)
        throws Exception {
    String message = "TESTING";
    return message;
}

但是我收到403错误.

But I'm getting a 403 error.

使用Spring Security和Java配置,默认情况下启用CSRF保护. 在这种情况下,如果使用POST方法向REST端点发出Ajax请求,则会收到csrf令牌丢失错误.

Using Spring Security with Java configuration, CSRF protection is enabled by default. In this context, if you make an Ajax request to a REST endpoint using POST method, you will get a csrf token missing error.

要解决此问题,有两种选择:

To solve this, there are two options:

选项1:禁用csrf

@Override
protected void configure (HttpSecurity http) throws Exception {
    http.csrf().disable();
}

选项2:将csrf添加到ajax请求中.参见这里

Option 2: Add csrf to the ajax request. See here