Spring Security 3.2: @Autowire doesn't work with java configuration and custom AuthenticationProvider in Spring MVC application?

ε祈祈猫儿з 提交于 2019-11-29 00:13:10
pasemes

Figured out how to put it to work, although there still some issues unanswered.

1) I still don't know why Spring context initialization fails when UserService implements UserDetailsService. Given that I'm not seeing use for it, since I'm using a custom AuthenticationProvider, I just removed this implementation and things are ok for now. To the best of my knowledge (from what I could understand from my first initial reading of Spring Security reference documentation) providing a custom AuthenticationProvider or an UserDetailsService implementation are exclusive alternatives.

2) As noticed by one of the respondents (@Sotirios Delimanolis) I was instantiating ApplicatinoAuthenticationProvider by hand and since it wasn't being managed by Spring this instance would not have an UserService instance autowired into it. Based on this, I changed WebSecurityConfig to get an autowired instance of ApplicationAuthenticationProvider as can be seen below:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private ApplicationAuthenticationProvider authenticationProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
        authManagerBuilder.authenticationProvider(authenticationProvider);
    }
}

This wasn't still sufficient, because ApplicationAuthenticationProvider wasn't being autowired into WebSecurityConfig. Based on this link Spring Security 3.1.3 @Autowired not Work when using WebApplicationInitializer I noticed that this was because security config should have a component scan declaration too. Adding @ComponentScan(basePackages = {"com.mypackage"}) to WebSecurityConfig resolved the problem.

I'm going to assume that UserService is a class and has some @Transactional annotation either on itself or one of its methods.

You'll need to add CGLIB to your classpath and change your @EnableTransactionManagement to

@EnableTransactionManagement(proxyTargetClass = true)

so that Spring uses CGLIB proxying (which can proxy classes) instead of JKD proxies (which cannot).


Alternatively, you can create an interface UserService and implement (and annotate with @Service) a UserServiceImpl class. Your autowired UserService field would remain the same, but Spring will be able to use JDK proxies.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!