Search code examples
spring-bootspring-security

The use of Spring Security Meta Annotation


According to the issues:14480 and documentation, I hope to use Meta Annotation in Spring Security 6.3.3. But I still cannot enable the meta annotation correctly. I got the following error message:

org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'roles' cannot be found on object of type 'org.springframework.security.access.expression.method.MethodSecurityExpressionRoot' - maybe not public or not valid?

Here is my reproduced code:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@SpringBootApplication
@RestController
@EnableMethodSecurity
public class SpringProjectApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringProjectApplication.class, args);
    }

    @GetMapping(value = "/get")
    @HasAnyRole(roles = {"'USER'", "'ADMIN'"})
    public String get() {
        return "1";
    }

    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @PreAuthorize("hasAnyRole({roles})")
    public @interface HasAnyRole {
        String[] roles();
    }
}

The SpringBoot version I am using is 3.3.4 (corresponding to Spring Security version 6.3.3).

Did I miss something?


Solution

  • You are linking to the documentation but haven't followed it.

    If you look at the start of said documentation about templating you will see that it requires an additional bean to be registered. The PrePostTemplateDefaults needs to be active.

    @Bean
    static PrePostTemplateDefaults prePostTemplateDefaults() {
        return new PrePostTemplateDefaults();
    }
    

    This bean definition is the first in the part in the documentation about [templating2. Looking at your configuration that bean isn't there.