We secure endpoints by role to control who can access certain parts of an application. This keeps data safe and ensures users only see what they should.
Securing endpoints by role in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Spring Boot
@PreAuthorize("hasRole('ADMIN')") @GetMapping("/endpoint") public ResponseEntity<String> method() { // method code }
Use @PreAuthorize on controller methods to restrict access by role.
Roles usually start with 'ROLE_' prefix in Spring Security.
Examples
Spring Boot
@PreAuthorize("hasRole('ADMIN')") @GetMapping("/admin") public String adminPage() { return "Admin content"; }
Spring Boot
@PreAuthorize("hasAnyRole('USER', 'ADMIN')") @GetMapping("/dashboard") public String dashboard() { return "Dashboard content"; }
Spring Boot
@PreAuthorize("!hasRole('GUEST')") @GetMapping("/secure") public String secureArea() { return "Secure content"; }
Sample Program
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.
Spring Boot
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!"; } }
Important Notes
Make sure to enable method security with @EnableMethodSecurity in your configuration.
Roles in Spring Security usually have the prefix 'ROLE_'. For example, 'ROLE_ADMIN'.
Test your endpoints with different user roles to confirm security works as expected.
Summary
Use @PreAuthorize to secure endpoints by user roles.
Roles control who can access specific parts of your app.
Always test security rules to keep your app safe.
Practice
1. What is the primary purpose of using
@PreAuthorize in a Spring Boot application?easy
Solution
Step 1: Understand the role of @PreAuthorize
@PreAuthorize is an annotation used to secure methods by specifying access rules based on user roles or permissions.Step 2: Identify its main function
It restricts method access so only users with certain roles can execute them, enhancing security.Final Answer:
To restrict access to methods based on user roles -> Option DQuick Check:
@PreAuthorize controls access by roles [OK]
Hint: Remember @PreAuthorize controls method access by roles [OK]
Common Mistakes:
- Confusing @PreAuthorize with logging or formatting annotations
- Thinking it manages database transactions
- Assuming it handles response data formatting
2. Which of the following is the correct syntax to restrict access to a method only to users with the role 'ADMIN' using
@PreAuthorize?easy
Solution
Step 1: Understand the hasRole syntax
ThehasRole('ROLE_NAME')expression inside @PreAuthorize restricts access to users with that role.Step 2: Match the role 'ADMIN'
To restrict to 'ADMIN', usehasRole('ADMIN'). Other options either allow all or restrict to different roles.Final Answer:
@PreAuthorize("hasRole('ADMIN')") -> Option AQuick Check:
Correct role syntax = @PreAuthorize("hasRole('ADMIN')") [OK]
Hint: Use hasRole('ROLE_NAME') exactly for role checks [OK]
Common Mistakes:
- Using wrong role names like 'USER' instead of 'ADMIN'
- Using permitAll or denyAll when restricting by role
- Incorrect syntax like missing quotes
3. Given the following method in a Spring Boot controller:
What will happen if a user with role 'EMPLOYEE' tries to access
@PreAuthorize("hasRole('MANAGER')")
public String getManagerData() {
return "Manager Info";
}What will happen if a user with role 'EMPLOYEE' tries to access
getManagerData()?medium
Solution
Step 1: Check the role restriction
The method is restricted to users with role 'MANAGER' only.Step 2: Analyze access for 'EMPLOYEE' role
A user with role 'EMPLOYEE' does not meet the role requirement, so access is denied by Spring Security.Final Answer:
Access is denied and an error is thrown -> Option AQuick Check:
Role mismatch causes access denial [OK]
Hint: Access denied if user role doesn't match @PreAuthorize role [OK]
Common Mistakes:
- Assuming method returns data regardless of role
- Thinking method returns null or empty string on denial
- Ignoring Spring Security's access control
4. Consider this Spring Boot method:
Which of the following is a common mistake that will cause this security annotation to fail?
@PreAuthorize("hasRole('ADMIN')")
public String adminPanel() {
return "Welcome Admin";
}Which of the following is a common mistake that will cause this security annotation to fail?
medium
Solution
Step 1: Check role name case sensitivity
Spring Security roles are case sensitive. Using lowercase 'admin' instead of 'ADMIN' causes the check to fail.Step 2: Verify other options
@PreAuthorize must be above the method, returning String is valid, and missing import causes compile error but not security failure.Final Answer:
Using hasRole('admin') with lowercase role name -> Option BQuick Check:
Role names are case sensitive [OK]
Hint: Role names must match case exactly in hasRole() [OK]
Common Mistakes:
- Using lowercase role names
- Ignoring import statements causing compile errors
- Misplacing @PreAuthorize annotation
5. You want to secure two endpoints in your Spring Boot app: one accessible only by users with role 'USER', and another accessible only by users with role 'ADMIN'. Which is the best way to implement this using
@PreAuthorize?hard
Solution
Step 1: Understand role-specific access
Each endpoint should restrict access to its specific role only, not both roles together.Step 2: Apply correct @PreAuthorize annotations
Use@PreAuthorize("hasRole('USER')")on the user endpoint and@PreAuthorize("hasRole('ADMIN')")on the admin endpoint to enforce separate access.Final Answer:
Use @PreAuthorize("hasRole('USER')") on the user method and @PreAuthorize("hasRole('ADMIN')") on the admin method -> Option CQuick Check:
Separate roles need separate @PreAuthorize rules [OK]
Hint: Assign each method its specific role in @PreAuthorize [OK]
Common Mistakes:
- Using combined roles on both methods allowing wrong access
- Using permitAll and checking roles manually inside methods
- Using hasAnyRole on both methods ignoring role separation
