BAEL-3972: Move code examples to new package

This commit is contained in:
Michael Pratt 2020-05-06 10:38:16 -06:00
parent 0690a9deae
commit 9770eda888
5 changed files with 82 additions and 58 deletions

View File

@ -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

View File

@ -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<Iterable<Task>> getAlManagerTasks() {
Iterable<Task> tasks = taskService.findAll();
return ResponseEntity.ok().body(tasks);
}
/**
* Example of restricting specific endpoints to specific roles using SecurityContext.
*/
@GetMapping("/actuator")
public ResponseEntity<Iterable<Task>> 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<Task> tasks = taskService.findAll();
return ResponseEntity.ok().body(tasks);
}
/**
* Example of restricting specific endpoints to specific roles using UserDetailsService.
*/
@GetMapping("/admin")
public ResponseEntity<Iterable<Task>> 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<Task> tasks = taskService.findAll();
return ResponseEntity.ok().body(tasks);
}
/**
* Example of restricting specific endpoints to specific roles using HttpServletRequest.
*/
@GetMapping("/admin2")
public ResponseEntity<Iterable<Task>> getAlAdminTasksUsingServlet(HttpServletRequest request) {
if (!request.isUserInRole("ROLE_ADMIN")) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
Iterable<Task> tasks = taskService.findAll();
return ResponseEntity.ok().body(tasks);
}
}

View File

@ -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);
}
}

View File

@ -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 {
}

View File

@ -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();
}
}