I read from spring documentation that to enable dynamic method level meta annotations I need to configure a class called AnnotationTemplateExpressionDefaults.
I have done that here
@Bean
public AnnotationTemplateExpressionDefaults annotationTemplateExpressionDefaults(){
return new AnnotationTemplateExpressionDefaults();
}
I then configured an annotation called HasAnyRole
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize(value = "hasAnyRole({roles})")
public @interface HasAnyRole {
String[] roles();
}
Then I annotated a method with the has role and passed the following roles
@PostMapping("/create")
@HasAnyRole(roles = {"'MANAGING_DIRECTOR'","'OPERATIONS_MANAGER'","'PROJECT_MANAGER'"})
public ResponseEntity<APIResponse> createProject(@Valid @RequestBody ProjectCreationRequest projectCreationRequest)
throws ProjectNotCreatedException{
return projectService.generateProjectCreationRequest(projectCreationRequest);
}
When I called this method I got the error Failed to evaluate expression 'hasAnyRole({roles})'"
But on further research I am finding out that this does not work with PreAuthorize and I will need to either use AOP or create custom bean that I can use to resolve the annotation hasAnyRole.
My question is what am I doing wrong because i followed the documentation and still did not get the desired result
Comment From: kse-music
Based on your description, I don't see any issues in my local. Could you provide a minimal sample that reproduces the steps? I'd be happy to take a look.
Ps: I'm tested in Spring Boot 3.4.1.
Comment From: Omololu98
Based on your description, I don't see any issues in my local. Could you provide a minimal sample that reproduces the steps? I'd be happy to take a look.
Ps: I'm tested in Spring Boot 3.4.1.
I tested with 3.2.5, I would try testing with 3.4.1 and see if it's an issue with the version I'm working with
Comment From: Omololu98
So this worked when I changed to Spring boot 3.4.1 Thank you. Maybe the documentation should be more specific on the versions for better understanding