0
0
Spring Bootframework~5 mins

@PreAuthorize annotation in Spring Boot - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the @PreAuthorize annotation in Spring Boot?
The @PreAuthorize annotation is used to check if a user has the required permissions before allowing access to a method. It helps secure methods by defining access rules using expressions.
Click to reveal answer
beginner
How do you enable the use of @PreAuthorize annotations in a Spring Boot application?
You enable @PreAuthorize by adding @EnableMethodSecurity (or @EnableGlobalMethodSecurity(prePostEnabled = true) in older versions) to a configuration class. This activates method-level security checks.
Click to reveal answer
intermediate
What kind of expressions can you use inside @PreAuthorize?
You can use Spring Expression Language (SpEL) expressions like hasRole('ADMIN'), hasAuthority('permission'), or complex logical expressions combining roles and permissions.
Click to reveal answer
beginner
Example: What does @PreAuthorize("hasRole('ADMIN')") do?
It allows only users with the role ADMIN to access the annotated method. If the user lacks this role, access is denied before the method runs.
Click to reveal answer
intermediate
Can @PreAuthorize check conditions based on method parameters?
Yes, @PreAuthorize can use method parameters in expressions, for example: @PreAuthorize("#userId == authentication.principal.id") to allow access only if the user ID matches the logged-in user.
Click to reveal answer
What annotation must be added to enable @PreAuthorize in Spring Boot?
A<code>@EnableMethodSecurity</code>
B<code>@EnableWebSecurity</code>
C<code>@SpringBootApplication</code>
D<code>@ComponentScan</code>
Which expression checks if a user has the role 'USER' inside @PreAuthorize?
AhasRole('USER')
BhasAuthority('USER')
CisAuthenticated()
DpermitAll()
What happens if a user fails the @PreAuthorize check?
AMethod runs but returns null
BAccess is denied and method is not executed
CUser is redirected automatically
DMethod runs with limited permissions
Can @PreAuthorize use method parameters in its expression?
AOnly if parameters are primitive types
BNo, it only checks user roles
CYes, using parameter names with #
DOnly in controller classes
Which of these is a valid @PreAuthorize expression?
AisAnonymous() or hasAuthority('USER')
BpermitAll()
CallUsers()
DhasRole('ADMIN') and #id == authentication.principal.id
Explain how the @PreAuthorize annotation secures a method in Spring Boot.
Think about how you stop someone from entering a room unless they have a key.
You got /4 concepts.
    Describe how you would restrict a method to only allow access to users with a specific role and matching user ID parameter.
    Combine role check and parameter check in one expression.
    You got /4 concepts.