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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-08 06:09:04

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/39434971/how-set-up-headers-in-ajax-post-request-to-include-csrf-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!