Сперва сделал механизм сохранения рецепта в базу:
@PostMapping(value = "/foodArray", consumes = {"application/x-www-form-urlencoded"})
public String recipeAdd(@RequestParam(required = true) String name,
@RequestParam(required = true) String reciepe,
@RequestParam(required = true) int weight,
@RequestParam(required = true) int calories,
@RequestParam(required = true) String info,
@AuthenticationPrincipal User user){
Reciepe rec = new Reciepe(name, reciepe, weight, calories, info, user);
reciepeRepo.save(rec);
return "redirect:/foodArray";
}
Все нормально сохранялось и удалялось со страницы. Затем попробовал добавить авторизацию/регистрацию через Spring Security. Все работает, но перестал сохранять рецепты в базу, выдает ошибку 403 и больше вообще никакой инфы.
@Entity
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
@Enumerated(EnumType.STRING)
@ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
@CollectionTable(name = "roles")
private Set<Role> roles = new HashSet<>();
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
private Collection<? extends GrantedAuthority> getRoles() {
return roles;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getRoles();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
@Controller
@RequestMapping("/registration")
public class RegistrationController {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private UserRepo userRepo;
@GetMapping
public String registration(){
return "/registration";
}
@PostMapping
public String processUser(RegistrationForm form){
userRepo.save(form.toUser(passwordEncoder));
return "redirect:/login";
}
}
public class RegistrationForm {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User toUser(PasswordEncoder passwordEncoder){
User user = new User();
user.setUsername(username);
user.setPassword(passwordEncoder.encode(password));
user.setRoles(Collections.singleton(Role.USER));
return user;
}
}