I have my spring server working already.
I added the spring-security
dependency to the gradle.
logged in with the provided password, I can access all the pages with their links directly, and move from one page to another, except one page that I get a forbidden message (403) when I submit the details in it.
The page provide an image with checkboxes for the logged in user to design his/her taco and submit it to the orders page.
this part stopped working for no reason and started to give me the 403 message. what is the issue with it?
the dependency i used:
implementation("org.springframework.boot:spring-boot-starter-security")
the controller works fine until it reaches the @PostMapping
code:
@Controller
@RequestMapping("/design")
@SessionAttributes("tacoOrder")
class DesignTacoController(
@Autowired private val ingredientsRepository: IngredientsRepository
) {
@ModelAttribute
fun addIngredientsToModel(model: Model) {
val ingredients = ingredientsRepository.findAll()
val types: Array<Type> = Type.values()
for (type in types) {
model.addAttribute(
type.toString().lowercase(), //Name to be used in View
filterByType(ingredients.toList(), type)
) //Value
}
}
@ModelAttribute(name = "tacoOrder")
fun order(): TacoOrder {
return TacoOrder()
}
@ModelAttribute(name = "taco")
fun taco(): Taco {
return Taco()
}
@GetMapping
fun showDesignForm(): String = "design"
private fun filterByType(ingredients: List<Ingredients>, type: Type): Iterable<Ingredients> {
return ingredients
.stream()
.filter { it.type == type }
.collect(Collectors.toList())
}
@PostMapping
fun processTaco(
taco: Taco,
bindingResult: BindingResult,
@ModelAttribute tacoOrder: TacoOrder,
): String {
checkTaco(taco, bindingResult)
if (bindingResult.hasErrors()) return "design"
tacoOrder.addTaco(taco)
println("Processing Taco:$taco")
return "redirect:/orders/current"
}
private fun checkTaco(taco: Taco, bindingResult: BindingResult) {
if (taco.name.length < 5) bindingResult.addError(FieldError("name", "name", "Name Should be longer than 5 Characters."))
if (taco.ingredient.isEmpty()) bindingResult.addError(FieldError("taco", "ingredient", "You should have at least one ingredient."))
}
}
Spring Security enables CSRF protection by default, that caused the 403 response on the POST request.
you can either disable the CSRF from the configuration or add the csrf to the POST Request.
like for my situation i only needed to add one field to the form
th:action="@{/design}"
this is it...