I'm new in spring. I was trying to add a new goal to my database. Before I add spring security it's worked, but now if I click to add a new goal, I have a problem :
There was an unexpected error (type=Forbidden, status=403). Forbidden
My goat-add.html :
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Goals</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<header th:insert="blocks/header :: header"></header>
<div class="container mt-5 mb-5">
<h1>Your goals</h1>
<form action="/goal/add" method="post">
<input type="text" name="name" placeholder="Write your goal name" class="form-control"><br>
<textarea type="text" name="description" placeholder="Write your goal description" class="form-control"></textarea><br>
<button type="submit" class="btn btn-success">Add goal</button>
</form>
</div>
<div th:insert="blocks/footer :: footer"></div>
</body>
</html>
WebSecurityConfig class :
package com.evgzabozhan.GoatGoal.config;
import com.evgzabozhan.GoatGoal.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login","/registration").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService)
.passwordEncoder(NoOpPasswordEncoder.getInstance());
}
}
My controller :
package com.evgzabozhan.GoatGoal.controller;
import com.evgzabozhan.GoatGoal.model.Goal;
import com.evgzabozhan.GoatGoal.model.User;
import com.evgzabozhan.GoatGoal.repository.GoalRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.*;
@Controller
public class GoalController {
@Autowired
private GoalRepository goalRepository;
@GetMapping("/goal")
public String goal(Model model){
Iterable<Goal> goals = goalRepository.findAll();
model.addAttribute("goals",goals);
return "goal/goal-main";
}
@GetMapping("/goal/add")
public String getGoalAdd(Model model){
return "goal/goal-add";
}
@PostMapping("/goal/add")
public String postGoalAdd(@AuthenticationPrincipal User user,
@RequestParam String name,
@RequestParam String description, Model model){
Goal goal = new Goal(name,description,user);
goalRepository.save(goal);
model.addAttribute("message",user.getUsername());
return "redirect:/goal";
}
@GetMapping("/goal/{id}")
public String goalInfo(@PathVariable(value = "id") long id, Model model) {
if (!goalRepository.existsById(id)) {
return "redirect:/goal";
}
Optional<Goal> goal = goalRepository.findById(id);
ArrayList<Goal> result = new ArrayList<>();
goal.ifPresent(result::add);
model.addAttribute("goal", result);
return "goal/goal-info";
}
@GetMapping("/goal/{id}/edit")
public String goalEdit(@PathVariable(value = "id") long id, Model model){
if (!goalRepository.existsById(id)) {
return "redirect:/goal";
}
Optional<Goal> goal = goalRepository.findById(id);
ArrayList<Goal> result = new ArrayList<>();
goal.ifPresent(result::add);
model.addAttribute("goal", result);
return "goal/goal-edit";
}
@PostMapping("/goal/{id}/edit")
public String postGoalUpdate(@PathVariable(value = "id") long id,
@RequestParam String name,
@RequestParam String description,
Model model){
Goal goal = goalRepository.findById(id).orElseThrow();
goal.setName(name);
goal.setDescription(description);
goalRepository.save(goal);
return "redirect:/goal";
}
@PostMapping("/goal/{id}/remove")
public String postGoalRemove(@PathVariable(value = "id") long id, Model model){
Goal goal = goalRepository.findById(id).orElseThrow();
goalRepository.delete(goal);
return "redirect:/goal";
}
}
I read this problem can be if don't use csrf, but I don't understand how I can fix it.
All code there: https://github.com/evgzabozhan/GoatGoal
Thanks for your help!
I add .csrf.disable() in configure method and it's work.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/login","/registration").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
it's working because crsf is enabled on default in Spring