I\'m trying to create a Spring Boot 2.1 application. I have created the following rest controller ...
@RestController
@RequestMapping("/api/users")
pub
CustomUser
class which is subclass of org.springframework.security.core.userdetails.User
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collection;
import java.util.UUID;
public class CustomUser extends User {
private final UUID id;
public UUID getId() {
return id;
}
public CustomUser(UUID id, String username, String password,
Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
this.id = id;
}
public CustomUser(UUID id, String username, String password,
boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired,
boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities) {
super(username, password, enabled,
accountNonExpired, credentialsNonExpired,
accountNonLocked, authorities);
this.id = id;
}
}
DatabaseUserDetailsService
to return this CustomUser @Service
public class DatabaseUserDetailsService implements UserDetailsService {
@Autowired
private IUserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
User user = userRepository.findByEmail(username);
return new CustomUser(user.getId(), user.getUsername(),
user.getPassword(), user.getAuthorities());
}
}
Note
@EnableGlobalMethodSecurity
enabled, otherwise @PreAuthorize
is not evaluatedyou can create a service that does the check for you like this:
@Service
public class AuthenticatedUserService {
@Autowired
private IUserRepository userRepository;
public boolean hasId(UUID ID){
String username = SecurityContextHolder.getContext().getAuthentication().getPrincipal().getUsername();
User user = userRepository.findByEmail(username);
return user.getId().equals(id);
}
}
add this to your controller
@Autowired
private AuthenticatedUserService authenticatedUserService;
and replace preauth annotation by this one:
@PreAuthorize("@authenticatedUserService.hasId(#id)")