Bird
Raised Fist0
Spring Bootframework~20 mins

@PreAuthorize annotation in Spring Boot - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Spring Security Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when a user without the required role accesses a method annotated with @PreAuthorize?

Consider a Spring Boot method annotated with @PreAuthorize("hasRole('ADMIN')"). What is the behavior if a user with role USER tries to call this method?

Spring Boot
public class MyService {
    @PreAuthorize("hasRole('ADMIN')")
    public String adminOnlyMethod() {
        return "Secret Data";
    }
}
AThe method returns null without executing the logic.
BThe method executes but returns an empty string.
CThe method throws an AccessDeniedException and does not execute.
DThe method executes normally and returns "Secret Data".
Attempts:
2 left
💡 Hint

Think about what Spring Security does when authorization fails.

📝 Syntax
intermediate
2:00remaining
Which @PreAuthorize expression correctly checks if the user has either ROLE_ADMIN or ROLE_MANAGER?

Choose the correct @PreAuthorize expression to allow access if the user has ROLE_ADMIN or ROLE_MANAGER.

A@PreAuthorize("hasAnyRole('ADMIN', 'MANAGER')")
B@PreAuthorize("hasRole('ADMIN' && 'MANAGER')")
C@PreAuthorize("hasRole('ADMIN') && hasRole('MANAGER')")
D@PreAuthorize("hasRole('ADMIN') or hasRole('MANAGER')")
Attempts:
2 left
💡 Hint

Look for the expression that checks multiple roles correctly.

state_output
advanced
2:00remaining
What is the output when a method annotated with @PreAuthorize uses a SpEL expression referencing method parameters?

Given the method below, what will be the output if the user has username "alice" and calls getUserData("alice")?

Spring Boot
public class UserService {
    @PreAuthorize("#username == authentication.name")
    public String getUserData(String username) {
        return "Data for " + username;
    }
}
A"Data for null" is returned because username is not passed correctly.
BAccessDeniedException is thrown because the expression is invalid.
CNullPointerException occurs due to missing authentication object.
D"Data for alice" is returned because the username matches authentication name.
Attempts:
2 left
💡 Hint

Check how SpEL accesses method parameters and authentication info.

🔧 Debug
advanced
2:00remaining
Why does this @PreAuthorize expression cause a syntax error?

Identify the problem in this annotation:

@PreAuthorize("hasRole('ADMIN') and hasPermission(#id, 'read')")
AThe hasPermission function requires three arguments, so this is incomplete.
BThe expression uses 'and' instead of '&&' which causes a syntax error.
CThe method parameter #id is not accessible in the expression.
DThe expression is valid and causes no syntax error.
Attempts:
2 left
💡 Hint

Check the logical operators allowed in SpEL expressions.

🧠 Conceptual
expert
2:00remaining
How does @PreAuthorize differ from @PostAuthorize in Spring Security?

Choose the statement that best describes the difference between @PreAuthorize and @PostAuthorize.

A<code>@PreAuthorize</code> checks authorization before method execution; <code>@PostAuthorize</code> checks after method execution and can use the method's return value.
B<code>@PreAuthorize</code> is used only for roles; <code>@PostAuthorize</code> is used only for permissions.
CBoth annotations check authorization only before method execution but differ in syntax.
D<code>@PreAuthorize</code> checks authorization after method execution; <code>@PostAuthorize</code> checks before method execution.
Attempts:
2 left
💡 Hint

Think about when the security check happens relative to the method call.

Practice

(1/5)
1. What is the main purpose of the @PreAuthorize annotation in Spring Boot?
easy
A. To inject dependencies into a method
B. To log method execution time automatically
C. To restrict access to methods based on user roles or permissions before execution
D. To handle exceptions thrown by a method

Solution

  1. Step 1: Understand the role of @PreAuthorize

    This annotation is used to check if a user has the right role or permission before allowing method execution.
  2. Step 2: Compare with other options

    Logging, dependency injection, and exception handling are unrelated to @PreAuthorize.
  3. Final Answer:

    To restrict access to methods based on user roles or permissions before execution -> Option C
  4. Quick Check:

    Access control = A [OK]
Hint: Remember: @PreAuthorize controls access before method runs [OK]
Common Mistakes:
  • Confusing @PreAuthorize with logging or exception handling
  • Thinking it injects dependencies
  • Assuming it runs after method execution
2. Which of the following is the correct syntax to allow only users with role 'ADMIN' to access a method using @PreAuthorize?
easy
A. @PreAuthorize("denyAll()")
B. @PreAuthorize("hasRole('ADMIN')")
C. @PreAuthorize("permitAll()")
D. @PreAuthorize("hasAuthority('USER')")

Solution

  1. Step 1: Identify the correct expression for role checking

    The expression hasRole('ADMIN') checks if the user has the 'ADMIN' role.
  2. Step 2: Verify other options

    hasAuthority('USER') checks for a different role, permitAll() allows everyone, and denyAll() denies everyone.
  3. Final Answer:

    @PreAuthorize("hasRole('ADMIN')") -> Option B
  4. Quick Check:

    Role check syntax = D [OK]
Hint: Use hasRole('ROLE_NAME') to restrict by role [OK]
Common Mistakes:
  • Using wrong role name or authority
  • Confusing hasRole with hasAuthority
  • Using permitAll() when restriction is needed
3. Given the method below, what will happen if a user with role 'USER' calls it?
@PreAuthorize("hasRole('ADMIN')")
public String adminOnly() {
    return "Welcome Admin";
}
medium
A. Access denied error is thrown before method runs
B. The method executes and returns 'Welcome Admin'
C. The method executes but returns null
D. The method executes and returns 'Welcome User'

Solution

  1. Step 1: Understand the role restriction

    The method requires the user to have 'ADMIN' role to run.
  2. Step 2: Check user role and effect

    User has 'USER' role, not 'ADMIN', so access is denied before method runs.
  3. Final Answer:

    Access denied error is thrown before method runs -> Option A
  4. Quick Check:

    Role mismatch causes denial = A [OK]
Hint: If role missing, @PreAuthorize blocks method [OK]
Common Mistakes:
  • Assuming method runs anyway
  • Thinking it returns null instead of error
  • Confusing roles 'USER' and 'ADMIN'
4. Identify the error in this usage of @PreAuthorize:
@PreAuthorize("hasRole(ADMIN)")
public void secureMethod() { }
medium
A. Annotation should be @PostAuthorize instead
B. Method must return a value to use @PreAuthorize
C. No error, syntax is correct
D. Missing quotes around 'ADMIN' in hasRole expression

Solution

  1. Step 1: Check syntax of hasRole expression

    The role name must be a string inside quotes: hasRole('ADMIN').
  2. Step 2: Verify other options

    Return type is not required, @PreAuthorize is correct annotation, so no other errors.
  3. Final Answer:

    Missing quotes around 'ADMIN' in hasRole expression -> Option D
  4. Quick Check:

    Role names need quotes = C [OK]
Hint: Always put role names in quotes inside hasRole() [OK]
Common Mistakes:
  • Omitting quotes around role names
  • Confusing @PreAuthorize with @PostAuthorize
  • Thinking method must return a value
5. How would you use @PreAuthorize to allow access only if the user has either 'ADMIN' role or 'MANAGER' authority?
hard
A. @PreAuthorize("hasRole('ADMIN') or hasAuthority('MANAGER')")
B. @PreAuthorize("hasRole('ADMIN') and hasAuthority('MANAGER')")
C. @PreAuthorize("hasRole('ADMIN')") @PreAuthorize("hasAuthority('MANAGER')")
D. @PreAuthorize("permitAll()")

Solution

  1. Step 1: Understand logical operators in @PreAuthorize

    Use or to allow access if either condition is true.
  2. Step 2: Analyze options

    @PreAuthorize("hasRole('ADMIN') or hasAuthority('MANAGER')") uses or correctly; @PreAuthorize("hasRole('ADMIN') and hasAuthority('MANAGER')") requires both roles which is stricter; @PreAuthorize("hasRole('ADMIN')") @PreAuthorize("hasAuthority('MANAGER')") is invalid to use two annotations; @PreAuthorize("permitAll()") allows everyone.
  3. Final Answer:

    @PreAuthorize("hasRole('ADMIN') or hasAuthority('MANAGER')") -> Option A
  4. Quick Check:

    Use 'or' for either role or authority = B [OK]
Hint: Combine roles with 'or' inside one @PreAuthorize [OK]
Common Mistakes:
  • Using 'and' instead of 'or' when either role suffices
  • Trying to stack multiple @PreAuthorize annotations
  • Using permitAll() which allows everyone