This Spring Boot app has three endpoints. The '/admin' endpoint is only for ADMIN role users. The '/user' endpoint is for USER or ADMIN roles. The '/public' endpoint is open to all.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableMethodSecurity
public class RbacDemoApplication {
public static void main(String[] args) {
SpringApplication.run(RbacDemoApplication.class, args);
}
}
@RestController
class DemoController {
@GetMapping("/admin")
@PreAuthorize("hasRole('ADMIN')")
public String adminAccess() {
return "Welcome Admin!";
}
@GetMapping("/user")
@PreAuthorize("hasAnyRole('USER', 'ADMIN')")
public String userAccess() {
return "Welcome User or Admin!";
}
@GetMapping("/public")
public String publicAccess() {
return "Welcome Everyone!";
}
}