本文介绍了如何在Ajax POST请求中设置标头以包含CSRF令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

帮助设置标题以消除该错误消息:在请求参数'_csrf'或标题'X-CSRF-TOKEN'上发现无效的CSRF令牌'null'。

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}"/>

我的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请求的标头?
任何帮助将不胜感激。

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.

推荐答案

令牌可以如您的示例所示:

The token can be read as in your example:

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

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

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

这篇关于如何在Ajax POST请求中设置标头以包含CSRF令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 09:51