diff --git a/spring-security-modules/spring-security-core/README.md b/spring-security-modules/spring-security-core/README.md index e42dfecaa0..f28b3abb2b 100644 --- a/spring-security-modules/spring-security-core/README.md +++ b/spring-security-modules/spring-security-core/README.md @@ -8,6 +8,7 @@ This module contains articles about core Spring Security - [Introduction to Spring Method Security](https://www.baeldung.com/spring-security-method-security) - [Overview and Need for DelegatingFilterProxy in Spring](https://www.baeldung.com/spring-delegating-filter-proxy) - [Deny Access on Missing @PreAuthorize to Spring Controller Methods](https://www.baeldung.com/spring-deny-access) +- [Spring Security: Check If a User Has a Role in Java](https://www.baeldung.com/spring-security-check-user-role) ### Build the Project diff --git a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/controller/TaskController.java b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/controller/TaskController.java index 67072b5d61..7e6b2c3d9c 100644 --- a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/controller/TaskController.java +++ b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/controller/TaskController.java @@ -42,62 +42,4 @@ public class TaskController { return ResponseEntity.ok().body(tasks); } - - /** - * Example of restricting specific endpoints to specific roles using @PreAuthorize. - */ - @GetMapping("/manager") - @PreAuthorize("hasRole('ROLE_MANAGER')") - public ResponseEntity> getAlManagerTasks() { - Iterable tasks = taskService.findAll(); - - return ResponseEntity.ok().body(tasks); - } - - /** - * Example of restricting specific endpoints to specific roles using SecurityContext. - */ - @GetMapping("/actuator") - public ResponseEntity> getAlActuatorTasks() { - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - if (auth != null && auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ACTUATOR"))) - { - return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); - } - - Iterable tasks = taskService.findAll(); - - return ResponseEntity.ok().body(tasks); - } - - /** - * Example of restricting specific endpoints to specific roles using UserDetailsService. - */ - @GetMapping("/admin") - public ResponseEntity> getAlAdminTasks() { - if(userDetailsService != null) { - UserDetails details = userDetailsService.loadUserByUsername("pam"); - if (details != null && details.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ADMIN"))) { - return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); - } - } - - Iterable tasks = taskService.findAll(); - - return ResponseEntity.ok().body(tasks); - } - - /** - * Example of restricting specific endpoints to specific roles using HttpServletRequest. - */ - @GetMapping("/admin2") - public ResponseEntity> getAlAdminTasksUsingServlet(HttpServletRequest request) { - if (!request.isUserInRole("ROLE_ADMIN")) { - return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); - } - - Iterable tasks = taskService.findAll(); - - return ResponseEntity.ok().body(tasks); - } } diff --git a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/checkrolejava/App.java b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/checkrolejava/App.java new file mode 100644 index 0000000000..357583a572 --- /dev/null +++ b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/checkrolejava/App.java @@ -0,0 +1,11 @@ +package com.baeldung.checkrolejava; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class App { + public static void main(String[] args) { + SpringApplication.run(com.baeldung.app.App.class, args); + } +} diff --git a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/checkrolejava/UnauthorizedException.java b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/checkrolejava/UnauthorizedException.java new file mode 100644 index 0000000000..11fe9f9e5f --- /dev/null +++ b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/checkrolejava/UnauthorizedException.java @@ -0,0 +1,8 @@ +package com.baeldung.checkrolejava; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.UNAUTHORIZED) +public class UnauthorizedException extends RuntimeException { +} diff --git a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/checkrolejava/UserController.java b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/checkrolejava/UserController.java new file mode 100644 index 0000000000..3092e94c7f --- /dev/null +++ b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/checkrolejava/UserController.java @@ -0,0 +1,62 @@ +package com.baeldung.checkrolejava; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; + +import javax.servlet.http.HttpServletRequest; + +@Controller +public class UserController { + + @Autowired + private UserDetailsService userDetailsService; + + @PreAuthorize("hasRole('ROLE_ADMIN')") + @GetMapping("/user/{id}") + public String getUser(@PathVariable("id") String id) { + return "user"; + } + + @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_MANAGER')") + @GetMapping("/users") + public String getUsers() { + return "users"; + } + + @GetMapping("v2/user/{id}") + public String getUserUsingSecurityContext() { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth != null && auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ADMIN"))) { + return "user"; + } + + throw new UnauthorizedException(); + } + + @GetMapping("v2/users") + public String getUsersUsingDetailsService() { + UserDetails details = userDetailsService.loadUserByUsername("mike"); + if (details != null && details.getAuthorities().stream() + .anyMatch(a -> a.getAuthority().equals("ADMIN"))) { + return "users"; + } + + throw new UnauthorizedException(); + } + + @GetMapping("v3/users") + public String getUsers(HttpServletRequest request) { + if (request.isUserInRole("ROLE_ADMIN")) { + return "users"; + } + + throw new UnauthorizedException(); + } +}