Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How set up headers in ajax POST request to include CSRF token

Help set up headers to get rid of that error message: "Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'."

HTML:

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

My JS code:

var recipe = getRecipe();

var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
console.log(token);
console.log(header);
console.log(recipe);

var headers = {};
// How set up header for include CSRF-Token

$.ajax({
    url: "/recipe",
    type: "POST",
    dataType: "json",
    contentType: "application/json",
    headers: headers,
    data: JSON.stringify(recipe, null, "\t"),
    success: function(data) {
        console.log(data);
    },
    error : getErrorMsg
});

My controller code:

 @RequestMapping(value = "/recipe", method = RequestMethod.POST, produces = {"application/json"})
        @ResponseStatus(HttpStatus.OK)
        public @ResponseBody
        String addRecipe(@RequestBody String jsonString) {
            Recipe recipe = Recipe.fromJson(jsonString);
            recipe.setUser(getLoggedUser());
            if (recipe.getCategory() != null)
                recipe.setCategory(categoryService.findById(recipe.getCategory().getId()));

recipe.setFavoriteUsers(recipeService.findById(recipe.getId()).getFavoriteUsers());
            recipe.setPhoto(recipeService.findById(recipe.getId()).getPhoto());

            recipeService.save(recipe);
            return recipe.toJson();
        }

And Security config:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().hasRole("USER")
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .successHandler(loginSuccessHandler())
                .failureHandler(loginFailureHandler())
                .and()
            .logout()
                .permitAll()
                .logoutSuccessUrl("/login")
                .and()
            .csrf();
    }

How I can be sure csrf enabled? And how I have to set up headers of my ajax requests? Any help would be greatly appreciated.

like image 977
zzheads Avatar asked Oct 19 '25 14:10

zzheads


1 Answers

The token can be read as in your example:

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

You can then set up jQuery to send the CSRF token as a request header in all subsequent requests (you don't have to worry about it anymore):

$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('X-CSRF-TOKEN', token);
    }
});
like image 115
Gabor Lengyel Avatar answered Oct 22 '25 03:10

Gabor Lengyel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!