Method-level security helps protect specific parts of your app by controlling who can use certain methods. It keeps your app safe by checking permissions right where the action happens.
Method-level security in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
@PreAuthorize("hasRole('ROLE_NAME')")
public ReturnType methodName(Parameters) {
// method code
}@PreAuthorize is an annotation that checks permissions before the method runs.
You can use expressions like hasRole('ROLE_NAME') to specify who can access the method.
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) {
// delete user code
}@PreAuthorize("hasAuthority('READ_PRIVILEGE')") public List<Item> getItems() { // return items }
@PreAuthorize("#user.name == authentication.name")
public void updateProfile(User user) {
// update profile code
}This service has two methods. viewAccount can be used by users with the USER role. deleteAccount can only be used by ADMINs. This shows how to protect methods based on roles.
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; @Service public class AccountService { @PreAuthorize("hasRole('USER')") public String viewAccount() { return "Account details visible"; } @PreAuthorize("hasRole('ADMIN')") public String deleteAccount() { return "Account deleted"; } }
Enable method security in your Spring Boot app by adding @EnableMethodSecurity on a configuration class.
Use @PreAuthorize for checks before method runs, and @PostAuthorize for checks after method runs.
Make sure your security context is properly set up so roles and authorities are recognized.
Method-level security controls access to specific methods in your app.
Use @PreAuthorize with role or authority checks to protect methods.
This helps keep your app safe by checking permissions right where actions happen.
Practice
@PreAuthorize in Spring Boot method-level security?Solution
Step 1: Understand the role of
@PreAuthorize@PreAuthorizeis an annotation used to secure methods by specifying access rules based on roles or permissions.Step 2: Identify the correct purpose
It restricts method access to users who meet the specified security expression, such as having a certain role.Final Answer:
To restrict access to a method based on user roles or permissions -> Option BQuick Check:
Method-level security = restrict access [OK]
- Confusing @PreAuthorize with logging or retry mechanisms
- Thinking it injects dependencies
- Assuming it runs code before method execution without security checks
@PreAuthorize?Solution
Step 1: Recall the correct expression for role checking
The correct Spring Security expression to check a role ishasRole('ROLE_NAME').Step 2: Match the syntax
@PreAuthorize("hasRole('ADMIN')") useshasRole('ADMIN'), which is the standard and correct syntax.Final Answer:
@PreAuthorize("hasRole('ADMIN')") -> Option DQuick Check:
Role check syntax = hasRole('ROLE') [OK]
- Using hasPermission instead of hasRole for roles
- Using non-existent expressions like isUser or checkRole
- Missing quotes or wrong method names
getUserData()?
@PreAuthorize("hasRole('USER')")
public String getUserData() {
return "User Data";
}Solution
Step 1: Understand the effect of @PreAuthorize with hasRole
The annotation blocks method execution if the user does not have the required role.Step 2: Identify the behavior when role is missing
Spring Security throws an AccessDeniedException and prevents the method from running.Final Answer:
AccessDeniedException is thrown and method is not executed -> Option CQuick Check:
Missing role = AccessDeniedException [OK]
- Thinking method returns null instead of throwing exception
- Assuming method runs but logs warning
- Believing method returns data regardless of role
@PreAuthorize("hasRole(ADMIN)")
public void deleteUser() {
// delete logic
}Solution
Step 1: Check the syntax of hasRole expression
The role name must be a string inside quotes, likehasRole('ADMIN').Step 2: Identify the missing quotes
The code useshasRole(ADMIN)without quotes, causing a syntax error.Final Answer:
Missing quotes around 'ADMIN' in hasRole expression -> Option AQuick Check:
Role names need quotes in hasRole [OK]
- Forgetting quotes around role names
- Confusing @PreAuthorize with @PostAuthorize
- Thinking void methods cannot be secured
@PreAuthorize expression correctly implements this?Solution
Step 1: Understand the requirement for access
The method should allow access if the user has either the 'ADMIN' role or the 'WRITE_PRIVILEGE' permission.Step 2: Choose the correct logical operator
The logical OR operatororallows access if either condition is true, matching the requirement.Step 3: Verify syntax correctness
@PreAuthorize("hasRole('ADMIN') or hasPermission('WRITE_PRIVILEGE')") usesorand correct method calls with quotes, making it valid.Final Answer:
@PreAuthorize("hasRole('ADMIN') or hasPermission('WRITE_PRIVILEGE')") -> Option AQuick Check:
Use 'or' to allow either role or permission [OK]
- Using 'and' instead of 'or' when either condition suffices
- Using '&&' which is invalid in SpEL expressions
- Confusing xor with or logic
