Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery POST giving 403 forbidden error in spring mvc

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);
});

The controller code is :

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

But I'm getting a 403 error.

like image 373
user3729782 Avatar asked Aug 06 '14 11:08

user3729782


3 Answers

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:

Option 1: Disable csrf

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

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

like image 155
Emiliano Schiano Avatar answered Sep 20 '22 10:09

Emiliano Schiano


You might want to add the csrf token to the request.

Obtaining the token using JSTL should be pretty straightforward. If you are using Thymeleaf, here is how to obtain it.

<script th:inline="javascript">     /*<![CDATA[*/     var _csrf_token = /*[[${_csrf.token}]]*/ '';     var _csrf_param_name = /*[[${_csrf.parameterName}]]*/ '';     /*]]>*/ </script> 

Then, add it to your request:

var requestData = {     'paramA': paramA,     'paramB': paramB, }; requestData[_csrf_param_name] = _csrf_token; // Adds the token  $.ajax({     type: 'POST',     url: '...your url...',     data: requestData,     ... }); 

If everything goes well, the request should include something like _csrf:1556bced-b323-4a23-ba1d-5d15428d29fa (the csrf token) and you will get a 200 instead of a 403.

like image 35
izilotti Avatar answered Sep 19 '22 10:09

izilotti


This is an example of without disabling CSRF.

Step 1: In your header add CSRF like this

<meta th:name="${_csrf.parameterName}" th:content="${_csrf.token}"/>

Step 2: Make call with token

$( "#create_something" ).click(function() {

  var token = $("meta[name='_csrf']").attr("content");

  $.ajax({
    url : '/xxxxxxxxxxxx', // url to make request
    headers: {"X-CSRF-TOKEN": token}, //send CSRF token in header
    type : 'POST',
    success : function(result) {
        alert(result);
    }
  })
});
like image 36
VK321 Avatar answered Sep 17 '22 10:09

VK321