@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping("/user/{id}")
public String getUser(@PathVariable("id") String id) {
...
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_MANAGER')")
@GetMapping("/users")
public String getUsers() {
...
}
57.4.3. 从 HttpServletRequest 返回的 request 变量中判断角色
@GetMapping("/users")
public String getUsers(HttpServletRequest request) {
if (request.isUserInRole("ROLE_ADMIN")) {
...
}
}
57.4.4. getAuthentication() 获得角色
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null && auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ADMIN"))) {
...
}
57.4.5. UserDetailsService
@GetMapping("/users")
public String getUsers() {
UserDetails details = userDetailsService.loadUserByUsername("mike");
if (details != null && details.getAuthorities().stream()
.anyMatch(a -> a.getAuthority().equals("ADMIN"))) {
// ...
}
}