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

帮助设置标题以消除该错误消息:"Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'."

HTML:









我的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请求的标头?

任何帮助将不胜感激。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值