Bird
Raised Fist0
Spring Bootframework~10 mins

Securing endpoints by role in Spring Boot - Step-by-Step Execution

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
Concept Flow - Securing endpoints by role
User sends request
Spring Security intercepts
Check user authentication
Yes
Check user roles
Role matches
Allow access
Response sent
The request passes through Spring Security which checks if the user is authenticated and has the required role before allowing access to the endpoint.
Execution Sample
Spring Boot
http
  .authorizeHttpRequests(auth -> auth
    .requestMatchers("/admin/**").hasRole("ADMIN")
    .requestMatchers("/user/**").hasAnyRole("USER", "ADMIN")
    .anyRequest().authenticated()
  )
This code configures endpoint access so only users with ADMIN role can access /admin/**, users with USER or ADMIN role can access /user/**, and all other requests require authentication.
Execution Table
StepRequest URLUser RolesAuthentication?Role CheckAccess Result
1/admin/dashboard[ADMIN]YesHas ADMIN roleAccess Allowed
2/admin/dashboard[USER]YesMissing ADMIN roleAccess Denied
3/user/profile[USER]YesHas USER roleAccess Allowed
4/user/profile[GUEST]YesMissing USER or ADMIN roleAccess Denied
5/public/info[]NoNot authenticatedAccess Denied
💡 Access is denied if user is not authenticated or lacks required role; allowed only if both checks pass.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5
User Roles[][ADMIN][USER][USER][GUEST][]
Authenticationfalsetruetruetruetruefalse
Access ResultN/AAllowedDeniedAllowedDeniedDenied
Key Moments - 3 Insights
Why does a user with USER role get denied access to /admin/dashboard?
Because the endpoint requires ADMIN role, and the user only has USER role. See execution_table row 2 where role check fails.
What happens if a user is not authenticated at all?
Access is denied immediately before role checks. See execution_table row 5 where authentication is No and access is denied.
Can a user with ADMIN role access /user/profile?
Yes, because /user/** allows USER or ADMIN roles. See execution_table row 3 for USER role allowed, ADMIN role would also pass.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the access result for a user with ADMIN role requesting /admin/dashboard?
AAuthentication Required
BAccess Denied
CAccess Allowed
DRole Check Skipped
💡 Hint
Check execution_table row 1 under Access Result column.
At which step does the authentication fail?
AStep 5
BStep 3
CStep 2
DStep 1
💡 Hint
Look at the Authentication? column in execution_table.
If a user has roles [USER, ADMIN], what would be the access result for /user/profile?
AAccess Denied
BAccess Allowed
CAuthentication Denied
DRole Check Skipped
💡 Hint
Refer to execution_table row 3 and consider role matching logic.
Concept Snapshot
Securing endpoints by role in Spring Boot:
- Use authorizeHttpRequests() to set role rules.
- .requestMatchers("/path/**").hasRole("ROLE") restricts access.
- User must be authenticated and have required role.
- Access denied if either check fails.
- Roles are case-sensitive and usually prefixed with 'ROLE_'.
Full Transcript
In Spring Boot, securing endpoints by role means controlling who can access certain URLs based on their assigned roles. When a user sends a request, Spring Security first checks if the user is authenticated. If not, access is denied immediately. If authenticated, it checks if the user has the required role for the requested endpoint. For example, endpoints under /admin/** require the ADMIN role, while /user/** can be accessed by USER or ADMIN roles. If the user has the correct role, access is allowed; otherwise, it is denied. This ensures only authorized users can reach sensitive parts of the application.

Practice

(1/5)
1. What is the primary purpose of using @PreAuthorize in a Spring Boot application?
easy
A. To log user activities
B. To format the response data
C. To handle database transactions
D. To restrict access to methods based on user roles

Solution

  1. 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.
  2. Step 2: Identify its main function

    It restricts method access so only users with certain roles can execute them, enhancing security.
  3. Final Answer:

    To restrict access to methods based on user roles -> Option D
  4. Quick 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
A. @PreAuthorize("hasRole('ADMIN')")
B. @PreAuthorize("hasRole('USER')")
C. @PreAuthorize("permitAll()")
D. @PreAuthorize("denyAll()")

Solution

  1. Step 1: Understand the hasRole syntax

    The hasRole('ROLE_NAME') expression inside @PreAuthorize restricts access to users with that role.
  2. Step 2: Match the role 'ADMIN'

    To restrict to 'ADMIN', use hasRole('ADMIN'). Other options either allow all or restrict to different roles.
  3. Final Answer:

    @PreAuthorize("hasRole('ADMIN')") -> Option A
  4. Quick 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:
@PreAuthorize("hasRole('MANAGER')")
public String getManagerData() {
    return "Manager Info";
}

What will happen if a user with role 'EMPLOYEE' tries to access getManagerData()?
medium
A. Access is denied and an error is thrown
B. The method returns "Manager Info"
C. The method returns null
D. The method executes but returns an empty string

Solution

  1. Step 1: Check the role restriction

    The method is restricted to users with role 'MANAGER' only.
  2. 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.
  3. Final Answer:

    Access is denied and an error is thrown -> Option A
  4. Quick 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:
@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
A. Returning a String instead of void
B. Using hasRole('admin') with lowercase role name
C. Placing @PreAuthorize above the method
D. Not importing org.springframework.security.access.prepost.PreAuthorize

Solution

  1. Step 1: Check role name case sensitivity

    Spring Security roles are case sensitive. Using lowercase 'admin' instead of 'ADMIN' causes the check to fail.
  2. 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.
  3. Final Answer:

    Using hasRole('admin') with lowercase role name -> Option B
  4. Quick 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
A. Use @PreAuthorize("hasRole('USER') or hasRole('ADMIN')") on both methods
B. Use @PreAuthorize("hasAnyRole('USER', 'ADMIN')") on both methods
C. Use @PreAuthorize("hasRole('USER')") on the user method and @PreAuthorize("hasRole('ADMIN')") on the admin method
D. Use @PreAuthorize("permitAll()") on both methods and check roles inside method

Solution

  1. Step 1: Understand role-specific access

    Each endpoint should restrict access to its specific role only, not both roles together.
  2. 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.
  3. Final Answer:

    Use @PreAuthorize("hasRole('USER')") on the user method and @PreAuthorize("hasRole('ADMIN')") on the admin method -> Option C
  4. Quick 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