Role-based access control helps decide who can do what in an app. It keeps things safe by giving permissions based on user roles.
When you want only admins to change settings in your app.
When users should see only their own data, not others'.
When different teams have different access levels in a system.
When you want to protect sensitive parts of your website or API.
When you want to easily add or remove permissions by changing roles.
Syntax
Spring Boot
@PreAuthorize("hasRole('ROLE_NAME')")
public ReturnType methodName() {
// method code
}
Use @PreAuthorize on methods to restrict access based on roles.
Roles usually start with 'ROLE_' prefix by convention in Spring Security.
Examples
This method can only be accessed by users with the ADMIN role.
Spring Boot
@PreAuthorize("hasRole('ADMIN')")
public String adminOnly() {
return"Admin content";
}
This method allows access to users with either USER or ADMIN roles.
Spring Boot
@PreAuthorize("hasAnyRole('USER', 'ADMIN')")
public String userOrAdmin() {
return"User or Admin content";
}
This method denies access to users with the GUEST role.
Spring Boot
@PreAuthorize("!hasRole('GUEST')")
public String noGuest() {
return"Not for guests";
}
Sample Program
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.
Spring Boot
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!";
}
}
OutputSuccess
Important Notes
Make sure to enable method security with @EnableMethodSecurity in your config.
Roles are case-sensitive and usually prefixed with 'ROLE_'.
Access denied errors return HTTP 403 status by default.
Summary
Role-based access control restricts access based on user roles.
Use @PreAuthorize annotations on methods to enforce role checks.
Configure roles carefully to protect sensitive parts of your app.
Practice
(1/5)
1. What is the main purpose of role-based access control (RBAC) in a Spring Boot application?
easy
A. To restrict access to resources based on user roles
B. To improve application performance by caching data
C. To automatically generate user interfaces
D. To handle database transactions efficiently
Solution
Step 1: Understand RBAC concept
RBAC limits access to parts of an application depending on the roles assigned to users.
Step 2: Identify the purpose in Spring Boot
In Spring Boot, RBAC is used to protect resources by checking user roles before allowing access.
Final Answer:
To restrict access to resources based on user roles -> Option A
Quick Check:
RBAC controls access by roles = A [OK]
Hint: RBAC controls who can do what by roles [OK]
Common Mistakes:
Confusing RBAC with performance optimization
Thinking RBAC generates UI automatically
Mixing RBAC with database transaction handling
2. Which annotation is used in Spring Boot to enforce role-based access control on a method?
easy
A. @PreAuthorize
B. @Autowired
C. @RequestMapping
D. @Entity
Solution
Step 1: Identify role enforcement annotation
Spring Security uses @PreAuthorize to check roles before method execution.
Hint: Use @PreAuthorize to check roles on methods [OK]
Common Mistakes:
Using @RequestMapping for access control
Confusing @Autowired with security annotations
Mistaking @Entity for access control
3. Given the method annotation @PreAuthorize("hasRole('ADMIN')"), what will happen if a user with role USER tries to access this method?
medium
A. Access is granted because USER is a valid role
B. Method throws a syntax error
C. Access is denied because the user lacks ADMIN role
D. Access is granted only if the user is authenticated
Solution
Step 1: Understand the @PreAuthorize expression
The expression requires the user to have the ADMIN role to access the method.
Step 2: Check user role against requirement
A user with only USER role does not meet the ADMIN role requirement, so access is denied.
Final Answer:
Access is denied because the user lacks ADMIN role -> Option C
Quick Check:
Role check fails without ADMIN role = B [OK]
Hint: User must have exact role in @PreAuthorize to access [OK]
Common Mistakes:
Assuming any authenticated user can access
Thinking USER role is enough for ADMIN-only methods
Confusing syntax error with access denial
4. Consider this method in a Spring Boot controller:
@PreAuthorize("hasRole('ADMIN')")
public String adminPage() {
return "Welcome Admin";
}
What is the likely cause if users with ADMIN role still get access denied errors?
medium
A. The method must be static to work with @PreAuthorize
B. The role prefix 'ROLE_' is missing in the role check
C. The return type should be ResponseEntity<String>
D. The method should be annotated with @GetMapping instead
Solution
Step 1: Understand Spring Security role prefix
Spring Security by default adds 'ROLE_' prefix to roles internally.
Step 2: Check role naming in @PreAuthorize
Using hasRole('ADMIN') expects the granted authority to be 'ROLE_ADMIN'. If roles lack this prefix, access is denied.
Final Answer:
The role prefix 'ROLE_' is missing in the role check -> Option B
Quick Check:
Missing 'ROLE_' prefix causes access denial = D [OK]
Hint: Remember Spring Security adds 'ROLE_' prefix by default [OK]
Common Mistakes:
Thinking @GetMapping affects access control
Believing return type affects security
Assuming method must be static for @PreAuthorize
5. You want to restrict access to a service method so that only users with either ADMIN or MANAGER roles can call it. Which @PreAuthorize expression correctly enforces this?
hard
A. @PreAuthorize("hasRole('ADMIN,MANAGER')")
B. @PreAuthorize("hasRole('ADMIN', 'MANAGER')")
C. @PreAuthorize("hasRole('ADMIN') and hasRole('MANAGER')")
D. @PreAuthorize("hasAnyRole('ADMIN', 'MANAGER')")
Solution
Step 1: Understand role checks for multiple roles
To allow access if user has either ADMIN or MANAGER, use hasAnyRole('ADMIN', 'MANAGER').
Step 2: Analyze each option
@PreAuthorize("hasRole('ADMIN') and hasRole('MANAGER')") requires both roles (AND), which is too strict. @PreAuthorize("hasRole('ADMIN', 'MANAGER')") is invalid as hasRole accepts only one role. @PreAuthorize("hasAnyRole('ADMIN', 'MANAGER')") uses hasAnyRole which is concise and correct. @PreAuthorize("hasRole('ADMIN,MANAGER')") is invalid syntax.
Final Answer:
@PreAuthorize("hasAnyRole('ADMIN', 'MANAGER')") -> Option D
Quick Check:
Use hasAnyRole for multiple allowed roles = A [OK]
Hint: Use hasAnyRole for OR conditions on roles [OK]
Common Mistakes:
Using AND instead of OR for multiple roles
Passing multiple roles as a single string
Not using hasAnyRole for multiple roles
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.