jQuery POST在Spring MVC中给出403禁止的错误 [英] Jquery POST giving 403 forbidden error in spring mvc

查看:315
本文介绍了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

这篇关于jQuery POST在Spring MVC中给出403禁止的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆