Spring Security - Доступ запрещен
Хочу реализовать в своем проекте возможность подписок и подписчиков, когда вызываю метод, который добавляет текущего юзера в подписчики автору, то вылетает ошибка.
User (Entity)
@Entity
@Table(name = "sweater_user")
public class User implements UserDetails{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "Username should not be empty")
private String username;
@NotBlank(message = "Password should not be empty")
private String password;
@Email(message = "Email is not correct")
@NotBlank(message = "Email should not be empty")
private String email;
private String activationCode;
private boolean active;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(
name = "sweater_user_role",
joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")
)
private Collection<Role> roles;
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
private Collection<Message> messages;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(
name = "user_subscriptions",
joinColumns = @JoinColumn(name = "channel_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "subscriber_id", referencedColumnName = "id")
)
private Set<User> subscribers = new HashSet<>();
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(
name = "user_subscriptions",
joinColumns = @JoinColumn(name = "subscriber_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "channel_id", referencedColumnName = "id")
)
private Set<User> subscriptions = new HashSet<>();
public User(String username, String password, String email, String activationCode, boolean active, Collection<Role> roles) {
this.username = username;
this.password = password;
this.email = email;
this.activationCode = activationCode;
this.active = active;
this.roles = roles;
}
public User() {
}
public boolean isAdmin(){
return roles.contains(new Role("ADMIN"));
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return isActive();
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getRoles();
}
Controller
@GetMapping("subscribe/{author}")
public String subscribeOnAuthor(@AuthenticationPrincipal User currentUser,
@PathVariable("author") Long id){
User author = userRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("User not exists with id " + id));
author.getSubscribers().add(currentUser);
userRepository.save(author);
return "redirect:/main/" + author.getUsername();
}
Ошибка:
Forbidden
org.springframework.security.access.AccessDeniedException: Доступ запрещен
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:73)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.attemptAuthorization(AbstractSecurityInterceptor.java:239)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:208)
at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:58)
Ответы (1 шт):
Автор решения: Egor
→ Ссылка
Не вижу метода isActive
@Override
public boolean isEnabled() {
return isActive();
}
У тебя есть переменна active, попробуй возвращать её в isEnabled
@Override
public boolean isEnabled() {
return active;
}