Master Spring Security: Web Expression Auth & Advanced @PreAuthorize Techniques
This guide demonstrates how to implement Spring Security authentication and authorization using web expression-based rules, custom beans, path variables, multi‑condition expressions, and advanced @PreAuthorize methods, including parameter‑based checks, custom annotations, and custom logic services within a Spring Boot 2.4 application.
Environment: Spring Boot 2.4.12 with Spring Security 5.4.9.
Web expression based authentication and authorization
Advanced @PreAuthorize usage
Web expression based authentication and authorization
This section demonstrates several ways to perform authentication using Spring Security web expressions.
Referencing a bean in a web security expression
<code>@Component
public class WebSecurity {
public boolean check(Authentication authentication, HttpServletRequest request) {
// Require the current user to have the "bus:news:delete" authority
SimpleGrantedAuthority auth = new SimpleGrantedAuthority("bus:news:delete");
return authentication.getAuthorities().contains(auth);
}
}
http.authorizeRequests()
.antMatchers("/a/index1")
.access("@webSecurity.check(authentication,request)");
</code>Using path variables in a web security expression
<code>public boolean checkUserId(Authentication authentication, int id) {
if (!(authentication.getPrincipal() instanceof Users)) {
return false;
}
Users user = (Users) authentication.getPrincipal();
return user.getId().equals(String.valueOf(id));
}
http.authorizeRequests()
.antMatchers("/a/index2/{userId}")
.access("@webSecurity.checkUserId(authentication,#userId)");
</code>Multiple‑condition expression
<code>http.authorizeRequests()
.antMatchers("/a/index3")
.access("hasRole('USERS') and hasIpAddress('192.168.1.0/24')");
</code>Advanced @PreAuthorize usage
Authentication based on method parameters
<code>// Permission check logic
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
return targetDomainObject.equals(permission);
}
@PreAuthorize("hasPermission(#role, 'USERS')")
@GetMapping("/index4")
public Object index4(String role) {
return "index4 - " + role;
}
// Using an object
@PreAuthorize("hasPermission(#user, 'USERS')")
public Object index4(Users user) { … }
// Accessing object properties
@PreAuthorize("hasPermission(#user.name, 'admin')")
public Object index4(Users user) { … }
</code>Access based on parameter names
<code>// Using @P to name a parameter
@PreAuthorize("#u.name == authentication.name")
public Object index4(@P("u") Users user) { … }
// Using @Param to name a parameter
@PreAuthorize("#n == authentication.name")
public Object index4(@Param("n") String name);
</code>Custom authentication annotation
Annotations can be applied to any Spring Security method. JSR‑250 meta‑annotations are not supported.
<code>@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize("#u.name == authentication.name")
public @interface UsersPermission {}
@UsersPermission
public Object index4(@P("u") Users user);
</code>Custom authentication logic
<code>@PreAuthorize("@s.check('bus:news:update')")
@GetMapping("/index5")
public Object index5() {
return "index5";
}
</code>Custom authentication service implementation:
<code>public class AuthorityService {
public boolean check(String authority) {
Users users = getUsers();
if (users == null) {
return false;
}
Collection<? extends GrantedAuthority> authorities = users.getAuthorities();
SimpleGrantedAuthority auth = new SimpleGrantedAuthority(authority);
return authorities.contains(auth);
}
public Users getUsers() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
return null;
}
Object principal = authentication.getPrincipal();
if (principal instanceof Users) {
return (Users) principal;
}
return null;
}
}
</code>Summary
Web expression based authentication and authorization
Advanced @PreAuthorize usage
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.