Bird
Raised Fist0
Spring Bootframework~20 mins

Custom permission evaluator 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
🎖️
Custom Permission Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output when a user without the required permission tries to access a secured method?
Consider a Spring Boot application using a custom permission evaluator. The evaluator denies access if the user lacks the required permission. What happens when a user without permission calls a method secured with @PreAuthorize("hasPermission(#id, 'read')")?
Spring Boot
public class CustomPermissionEvaluator implements PermissionEvaluator {
    @Override
    public boolean hasPermission(Authentication auth, Object targetDomainObject, Object permission) {
        // returns true only if user has permission
        return auth.getAuthorities().stream()
            .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(permission.toString()));
    }

    @Override
    public boolean hasPermission(Authentication auth, Serializable targetId, String targetType, Object permission) {
        return false;
    }
}

// Usage in service
@PreAuthorize("hasPermission(#id, 'read')")
public String getData(Long id) {
    return "data";
}
ASpring Security throws an AccessDeniedException preventing method execution.
BThe method executes normally and returns "data".
CThe method returns null without exception.
DA runtime NullPointerException occurs due to missing permission.
Attempts:
2 left
💡 Hint
Think about what Spring Security does when permission checks fail.
📝 Syntax
intermediate
1:30remaining
Which option correctly implements the hasPermission method signature for checking permission by target ID and type?
You want to implement the hasPermission method in a custom permission evaluator that checks permission based on target ID and target type. Which method signature is correct?
Apublic boolean hasPermission(Authentication auth, String targetType, Serializable targetId, Object permission)
Bpublic boolean hasPermission(Authentication auth, Long targetId, String permission)
Cpublic boolean hasPermission(Authentication auth, Serializable targetId, String targetType, Object permission)
Dpublic boolean hasPermission(Authentication auth, Object targetDomainObject, Object permission)
Attempts:
2 left
💡 Hint
Check the PermissionEvaluator interface method signatures.
🔧 Debug
advanced
2:30remaining
Why does the custom permission evaluator always deny access even when the user has the correct authority?
Given this custom permission evaluator code, why does it always deny access? public class CustomPermissionEvaluator implements PermissionEvaluator { @Override public boolean hasPermission(Authentication auth, Object targetDomainObject, Object permission) { return auth.getAuthorities().stream() .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(permission.toString())); } @Override public boolean hasPermission(Authentication auth, Serializable targetId, String targetType, Object permission) { return false; } } User has authority "read" but access is denied.
AThe authorities list is empty because authentication is null.
BThe permission object passed is not a String, so equals comparison fails.
CThe hasPermission method with targetId and targetType always returns false, causing denial.
DThe permission evaluator is not registered as a bean, so it is not used.
Attempts:
2 left
💡 Hint
Check the type and value of the permission parameter in the equals check.
🧠 Conceptual
advanced
1:30remaining
What is the role of the custom permission evaluator in Spring Security?
In Spring Security, what is the main purpose of implementing a custom permission evaluator?
ATo handle session management and timeout policies.
BTo replace the AuthenticationManager for user login authentication.
CTo configure HTTP security rules like URL patterns and roles.
DTo provide fine-grained access control by evaluating permissions dynamically at method or domain object level.
Attempts:
2 left
💡 Hint
Think about what permission evaluation means beyond simple role checks.
state_output
expert
2:00remaining
What is the value of 'result' after evaluating this Spring EL expression with a custom permission evaluator?
Assume a method annotated with @PreAuthorize("hasPermission(#doc, 'write')") is called with a document object doc. The custom permission evaluator returns true only if the user has 'write' authority. Given the user has authorities ['read', 'write'], what is the value of the boolean variable result after evaluating the expression hasPermission(doc, 'write')?
Spring Boot
Authentication auth = // user with authorities ['read', 'write']
Document doc = new Document();
boolean result = customPermissionEvaluator.hasPermission(auth, doc, "write");
Atrue
Bfalse
Cnull
DThrows AccessDeniedException
Attempts:
2 left
💡 Hint
Check if the user authorities contain the required permission string.

Practice

(1/5)
1. What is the main purpose of a Custom PermissionEvaluator in Spring Boot security?
easy
A. To handle database connections securely
B. To replace the entire Spring Security framework
C. To define custom rules for checking user permissions in a reusable way
D. To manage user sessions automatically

Solution

  1. Step 1: Understand the role of PermissionEvaluator

    The PermissionEvaluator interface allows defining custom logic to check if a user has permission to perform an action.
  2. Step 2: Identify the purpose of custom implementation

    Implementing a custom PermissionEvaluator lets you write your own rules that can be reused across your application for security checks.
  3. Final Answer:

    To define custom rules for checking user permissions in a reusable way -> Option C
  4. Quick Check:

    Custom PermissionEvaluator = Custom reusable permission rules [OK]
Hint: Custom PermissionEvaluator defines reusable permission rules [OK]
Common Mistakes:
  • Thinking it replaces Spring Security entirely
  • Confusing it with session management
  • Assuming it manages database connections
2. Which method must you override when implementing a PermissionEvaluator to check permissions based on a target domain object?
easy
A. checkPermission(Authentication authentication, String permission)
B. hasPermission(Authentication authentication, Object targetDomainObject, Object permission)
C. evaluatePermission(User user, String permission)
D. validatePermission(Object targetDomainObject)

Solution

  1. Step 1: Recall PermissionEvaluator interface methods

    PermissionEvaluator has two methods: one with targetDomainObject and one with targetId and targetType.
  2. Step 2: Identify the method for domain object permission check

    The method hasPermission(Authentication authentication, Object targetDomainObject, Object permission) is used to check permissions on a domain object.
  3. Final Answer:

    hasPermission(Authentication authentication, Object targetDomainObject, Object permission) -> Option B
  4. Quick Check:

    Domain object permission method = hasPermission with targetDomainObject [OK]
Hint: Override hasPermission with targetDomainObject for object checks [OK]
Common Mistakes:
  • Choosing methods not in PermissionEvaluator interface
  • Confusing method parameters
  • Using method names that don't exist
3. Given this custom PermissionEvaluator method snippet:
public boolean hasPermission(Authentication auth, Object target, Object perm) {
  if (auth == null || target == null || !(perm instanceof String)) {
    return false;
  }
  String permission = (String) perm;
  User user = (User) auth.getPrincipal();
  return user.getRoles().contains(permission);
}

What will be the result if auth is null?
medium
A. Returns false immediately
B. Throws NullPointerException
C. Returns true by default
D. Ignores null and continues

Solution

  1. Step 1: Analyze the null check at method start

    The method checks if auth is null and returns false immediately if so.
  2. Step 2: Understand the flow when auth is null

    Since auth == null triggers return false, no further code runs and no exception occurs.
  3. Final Answer:

    Returns false immediately -> Option A
  4. Quick Check:

    Null auth returns false immediately [OK]
Hint: Null checks return false early to avoid exceptions [OK]
Common Mistakes:
  • Assuming NullPointerException will be thrown
  • Thinking it returns true by default
  • Ignoring the null check logic
4. You wrote this custom PermissionEvaluator method:
public boolean hasPermission(Authentication auth, Object target, Object perm) {
  String permission = (String) perm;
  User user = (User) auth.getPrincipal();
  return user.getRoles().contains(permission);
}

What is the main problem with this code?
medium
A. It should return true by default
B. Casting perm to String is unnecessary
C. User roles cannot be checked this way
D. It lacks null checks and may throw NullPointerException

Solution

  1. Step 1: Check for missing null validations

    The method does not check if auth, perm, or auth.getPrincipal() are null before casting or calling methods.
  2. Step 2: Understand consequences of missing null checks

    If any are null, the code will throw NullPointerException at runtime.
  3. Final Answer:

    It lacks null checks and may throw NullPointerException -> Option D
  4. Quick Check:

    Missing null checks cause runtime exceptions [OK]
Hint: Always add null checks before casting or method calls [OK]
Common Mistakes:
  • Ignoring null safety
  • Thinking casting is always safe
  • Assuming roles check is invalid
5. You want to create a custom PermissionEvaluator that allows a user to edit a document only if they have the "EDITOR" role and the document status is "DRAFT".
Which code snippet correctly implements this logic inside hasPermission?
hard
A. if (auth == null || target == null) return false; User user = (User) auth.getPrincipal(); Document doc = (Document) target; return user.getRoles().contains("EDITOR") && "DRAFT".equals(doc.getStatus());
B. User user = (User) auth.getPrincipal(); Document doc = (Document) target; return user.getRoles().contains("EDITOR") || doc.getStatus().equals("DRAFT");
C. if (auth == null) return true; Document doc = (Document) target; return doc.getStatus() == "DRAFT";
D. User user = (User) auth.getPrincipal(); return user.getRoles().contains("EDITOR");

Solution

  1. Step 1: Check for null authentication and target

    Security checks should return false if authentication or target is null to avoid errors.
  2. Step 2: Verify user role and document status conditions

    The user must have "EDITOR" role and the document status must be exactly "DRAFT" for permission to be granted.
  3. Step 3: Confirm correct logical operator usage

    Both conditions must be true, so use logical AND (&&), not OR (||).
  4. Final Answer:

    if (auth == null || target == null) return false; User user = (User) auth.getPrincipal(); Document doc = (Document) target; return user.getRoles().contains("EDITOR") && "DRAFT".equals(doc.getStatus()); -> Option A
  5. Quick Check:

    Check nulls + role AND status = correct logic [OK]
Hint: Use && to combine role and status checks with null safety [OK]
Common Mistakes:
  • Using || instead of && for both conditions
  • Not checking for null auth or target
  • Comparing strings with == instead of equals()