Search code examples
javaspringspring-security

What is the intended replacement for .not() in Spring Security 6 HttpSecurity?


In Spring Security 5 you can configure your HttpSecurity like this:

http.antMatcher("/**")
    .authorizeRequests()
        .antMatchers("/").not().hasRole("INVITED")
        .antMatchers("/forgot-password").not().authenticated()

In Spring Security 6, there is no longer any not() method in the new system:

http.securityMatcher("/**")
    .authorizeHttpRequests((authorize) -> authorize
        .requestMatchers("/").???.hasRole("INVITED")
        .requestMatchers("/forgot-password").???.authenticated()
    )

What is the intended way to negate authorization expressions like this in Spring Security 6?


Solution

  • As far as I can tell, there is no replacement, but you can implement one yourself:

    public static <T> AuthorizationManager<T> not(AuthorizationManager<T> manager) {
        return (authentication, object) -> {
            AuthorizationDecision decision = manager.check(authentication, object);
            if (decision == null) {
                return null;
            } else {
                return new AuthorizationDecision(!decision.isGranted());
            }
        };
    }
    

    This can then be combined with other static imports from org.springframework.security.authorization:

    http.securityMatcher("/**")
        .authorizeHttpRequests((authorize) -> authorize
            .requestMatchers("/").access(not(hasRole("INVITED")))
            .requestMatchers("/forgot-password").access(not(authenticated()))
        )