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.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Master Spring Security: Web Expression Auth & Advanced @PreAuthorize Techniques

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

@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)");

Using path variables in a web security expression

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)");

Multiple‑condition expression

http.authorizeRequests()
    .antMatchers("/a/index3")
    .access("hasRole('USERS') and hasIpAddress('192.168.1.0/24')");

Advanced @PreAuthorize usage

Authentication based on method parameters

// 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) { … }

Access based on parameter names

// 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);

Custom authentication annotation

Annotations can be applied to any Spring Security method. JSR‑250 meta‑annotations are not supported.

@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize("#u.name == authentication.name")
public @interface UsersPermission {}

@UsersPermission
public Object index4(@P("u") Users user);

Custom authentication logic

@PreAuthorize("@s.check('bus:news:update')")
@GetMapping("/index5")
public Object index5() {
    return "index5";
}

Custom authentication service implementation:

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;
    }
}

Summary

Web expression based authentication and authorization

Advanced @PreAuthorize usage

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Spring BootAuthorizationspring-securityPreAuthorizeWeb Expressions
Spring Full-Stack Practical Cases
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.