gpt4 book ai didi

ajax - 如何在 ajax POST 请求中设置 header 以包含 CSRF token

转载 作者:行者123 更新时间:2023-12-05 02:20:21 25 4
gpt4 key购买 nike

帮助设置 header 以消除该错误消息:“在请求参数‘_csrf’或 header ‘X-CSRF-TOKEN’上发现无效的 CSRF token ‘null’。”

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

我的 Controller 代码:

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

最佳答案

token 可以像您的示例一样读取:

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

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

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

关于ajax - 如何在 ajax POST 请求中设置 header 以包含 CSRF token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39434971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com