I wrote my implementation of UserDetails in order to change the login and user roles. With the login, everything turned out to be quite simple, but I had problems with the roles. I don't understand what I need to do in order to change the default CUSTOMER role to another SELLER role
@ToString
public class CustomUserDetails implements UserDetails {
@ToString.Exclude
private Account account;
private final long serialVersionUID = 1L;
public CustomUserDetails(Account account) {
this.account = account;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_" + this.account.getRole().getAuthority()));
return authorities;
}
public void setRole(Role role) {
this.account.setRole(role);
}
@Override
public String getPassword() {
return this.account.getPassword();
}
@Override
public String getUsername() {
return this.account.getLogin();
}
public void setUsername(String username) {
this.account.setLogin(username);
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
Perhaps I should have been more specific about my question. But. I found a solution to this problem for myself. Maybe my method will help someone.
My CustomUserDetailsService:
My CustomUserDetails:
Method in the controller that changes data in the user session (needs refactoring):
Thus, I managed to achieve a dynamic change of roles for the user. If you have any suggestions on how my method can be improved, I'd love to hear it.