This Spring Boot app has three endpoints. The /admin endpoint is only for ADMIN role users. The /user endpoint is only for USER role users. The /public endpoint is open to everyone.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class RoleSecurityApp {
public static void main(String[] args) {
SpringApplication.run(RoleSecurityApp.class, args);
}
}
@RestController
class MyController {
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin")
public String adminEndpoint() {
return "Welcome Admin!";
}
@PreAuthorize("hasRole('USER')")
@GetMapping("/user")
public String userEndpoint() {
return "Welcome User!";
}
@GetMapping("/public")
public String publicEndpoint() {
return "Welcome Guest!";
}
}