Describe the bug
The application fails when I try to override GlobalMethodSecurityConfiguration class to implement custom permission evaluator, with the following error:
The bean 'methodSecurityInterceptor', defined in class path resource [org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.class], could not be registered. A bean with that name has already been defined in class path resource [com/example/MethodSecurityConfiguration.class] and overriding is disabled.
To Reproduce
Add Spring Security module and create a class overrding GlobalMethodSecurityConfiguration with @Configuration annotation or simply build and run this project.
Expected behavior Everything should work properly.
Sample https://github.com/akefirad/bad-spring-security
Remarks
Interestingly, if you move the @EnableGlobalMethodSecurity(prePostEnabled = true) annotation from Application class to somewhere else (e.g. on the class overriding GlobalMethodSecurityConfiguration) everything works just fine.
Not sure what the issue is.
Comment From: rwinch
Thanks for the report @akefirad
I try to override GlobalMethodSecurityConfiguration class to implement custom permission evaluator
There is no need to extend GlobalMethodSecurityConfiguration. You can just provide a PermissionEvaluator bean and it will be used.
The error is expected behaviour. The GlobalMethodSecurityConfiguration Javadoc states:
Base Configuration for enabling global method security. Classes may extend this class to customize the defaults, but must be sure to specify the EnableGlobalMethodSecurity annotation on the subclass.
This is necessary so that Spring Security can detect if GlobalMethodSecurityConfiguration needs imported or not. If we do anything to try and prevent this, it will trigger eager bean initialization because AOP related beans need to be created very early. Eager bean initialization can trigger beans to not be proxied properly which would mean security, transactions, and other AOP would not be applied properly.