This is my Role enum
public enum Role implements GrantedAuthority {
ADMIN,
USER;
@Override
public String getAuthority() {
return this.name();
}
}
I had to implement GrantedAuthorities here because UserDetails implementation needs it. Here is my impl of UserDetails
public class AuthenticatedUser implements UserDetails {
User user;
@Autowired
public AuthenticatedUser(User user) {
this.user = user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return user.getRoles();
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return user.isEnabled();
}
public int getId() {
return user.getId();
}
public User getUser() {
return user;
}
}
So what I do is just return Roles as GrantedAuthorities. But here is the problem. I want to use hasRoles() in SpringSecurity and I can't. It understand only hasAnyAuthority()
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.requestMatchers(req -> req.getRequestURI().contains("admin")).hasAnyAuthority(Role.ADMIN.getAuthority())
// .anyRequest().authenticated()
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.headers().frameOptions().disable()
.and()
.httpBasic();
}
The question is how is this possible to override UserDetails and use hasRoles?