如何在ajax POST请求中设置标头以包含CSRF令牌

时间:2016-09-11 10:07:10

标签: ajax spring-security csrf

帮助设置标题以消除该错误消息:"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}"/>
&#13;
&#13;
&#13;

我的JS代码:

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

我的控制器代码:

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

安全配置:

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

我如何确保启用csrf? 我如何设置我的ajax请求的标头? 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

可以在示例中读取令牌:

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

然后,您可以设置jQuery以在所有后续请求中将CSRF令牌作为请求标头发送(您不必再担心它):

$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('X-CSRF-TOKEN', token);
    }
});