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

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

推荐答案

在 Java 配置中使用 Spring Security,默认启用 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天全站免登陆