Hilfe Header einrichten dieser Fehlermeldung loszuwerden: "Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'."
Wie einrichten Header in Ajax-POST-Anfrage enthalten CSRF-Token
HTML:
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
Mein 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
});
Mein Controllercode:
@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();
}
und Sicherheit 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();
}
Wie ich sicher csrf aktiviert werden kann? Und wie muss ich Header meiner Ajax-Anfragen einrichten? Jede Hilfe würde sehr geschätzt werden.