0
0
Spring Bootframework~30 mins

@PreAuthorize annotation in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Using @PreAuthorize Annotation in Spring Boot
📖 Scenario: You are building a simple Spring Boot REST API for a library system. You want to control access to certain endpoints based on user roles.
🎯 Goal: Learn how to use the @PreAuthorize annotation to restrict access to controller methods by user roles.
📋 What You'll Learn
Create a Spring Boot controller class named BookController
Add a method getAllBooks() that returns a list of book titles
Add a method addBook(String title) to add a new book
Use @PreAuthorize to allow only users with role ROLE_USER to access getAllBooks()
Use @PreAuthorize to allow only users with role ROLE_ADMIN to access addBook(String title)
💡 Why This Matters
🌍 Real World
Role-based access control is common in web applications to protect sensitive operations and data.
💼 Career
Understanding @PreAuthorize and method security is essential for backend developers working with Spring Boot to build secure APIs.
Progress0 / 4 steps
1
Create the BookController class with a list of books
Create a class called BookController annotated with @RestController. Inside it, create a private List<String> called books initialized with "Spring Basics" and "Java Fundamentals".
Spring Boot
Need a hint?

Use @RestController above the class. Initialize books with new ArrayList<>(List.of(...)).

2
Add a configuration variable for role prefix
Add a private static final String variable called ROLE_PREFIX and set it to "ROLE_" inside the BookController class.
Spring Boot
Need a hint?

Define ROLE_PREFIX as a constant string with value "ROLE_".

3
Add methods with @PreAuthorize annotations
Add a method getAllBooks() that returns List<String> and is annotated with @PreAuthorize("hasRole('USER')"). Add another method addBook(String title) annotated with @PreAuthorize("hasRole('ADMIN')") that adds the title to books.
Spring Boot
Need a hint?

Use @PreAuthorize with hasRole('USER') for getAllBooks() and hasRole('ADMIN') for addBook(String title).

4
Add class-level security annotation
Add the @EnableMethodSecurity annotation above the BookController class to enable method-level security.
Spring Boot
Need a hint?

Place @EnableMethodSecurity above the class declaration to activate method security.