Reputation: 2649
I'm trying to use Spring's expression language (SpEL) to pass a property from my application.yml
file into a SpEL method call.
I'm in a Spring Boot and Spring Security environment, and I'm trying to do this in the @PreAuthorize
annotation. I'm able to call the method hasAuthority()
without issue like so:
@PreAuthorize("hasAuthority('APP_USER')")
This works fine. It verifies the user has the APP_USER
authorization token. However, I want to externalize this value to configuration as a property. This doesn't work:
@PreAuthorize("hasAuthority(#systemProperties.get('app.auth.readToken'))")
I've also tried
@PreAuthorize("hasAuthority(#environment( app.auth.readToken ))")
and
@PreAuthorize("hasAuthority(${app.auth.readToken})")
So, how can I use SpEL to pass an application property as a SpEL method parameter? Is this possible?
Upvotes: 0
Views: 3419
Reputation: 5813
You can access the PropertyResolver
within the annotation with @propertyResolver
.
@PreAuthorize("hasRole(@propertyResolver.getProperty('app.auth.readToaken'))")
If this isn't working, you can provide a properties @Bean
in you configuration to load your properties. Then just access that bean instead of propertyResolver
. Here is example of loading a yml
file.
@Bean
public Properties properties() {
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new ClassPathResource("application.yml")); //the yml file
return yaml.getObject();
}
and used in an annotation...
@PreAuthorize("hasRole(@properties.getProperty('app.auth.readToaken'))")
Upvotes: 2