java Spring security 无法自动装配 UserDetailsService
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34431342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring security Cant autowire UserDetailsService
提问by Maciej
I got stuck trying to add authentication from database.
我在尝试从数据库添加身份验证时遇到困难。
Here is error log:
这是错误日志:
23-Dec-2015 08:24:32.819 SEVERE [localhost-startStop-1] org.springframework.web.context.ContextLoader.initWebApplicationContext Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.security.core.userdetails.UserDetailsService kamienica.configuration.SecurityConfig.userDetailsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.core.userdetails.UserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=customUserDetailsService)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586) at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1750) at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.security.core.userdetails.UserDetailsService kamienica.configuration.SecurityConfig.userDetailsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.core.userdetails.UserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=customUserDetailsService)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289) ... 26 more Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.core.userdetails.UserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=customUserDetailsService)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1103) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:963) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480) ... 28 more
2015 年 12 月 23 日 08:24:32.819 严重 [localhost-startStop-1] org.springframework.web.context.ContextLoader.initWebApplicationContext 上下文初始化失败 org.springframework.beans.factory.BeanCreationException:创建名为“securityConfig”的 bean 时出错: 自动装配依赖项的注入失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:无法自动装配字段:org.springframework.security.core.userdetails.UserDetailsService kamienica.configuration.SecurityConfig.userDetailsService; 嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:未找到类型为 [org.springframework.security.core.userdetails.UserDetailsService] 的合格 bean 依赖项:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586) at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1750) at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) ) 在 java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang。 Thread.run(Unknown Source) 引起:org.springframework.beans.factory.BeanCreationException:无法自动装配字段:org.springframework.security.core.userdetails.UserDetailsService kamienica.configuration.SecurityConfig.userDetailsService; 嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: Noqualifying bean of type [org. springframework.security.core.userdetails.UserDetailsService] 找到依赖项:预期至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注释:{@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=customUserDetailsService)} 在 org.springframework.beans.factory.annotation .AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508) 在 org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) 在 org.springframework.beans. .java:289) ... 26 多个原因:org.springframework。beans.factory.NoSuchBeanDefinitionException:找不到类型为 [org.springframework.security.core.userdetails.UserDetailsService] 的合格 bean 依赖项:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注释:{@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=customUserDetailsService)} 在 org.springframework.beans.factory.support .DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1103) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:963) 在 org.springframework.beans.factory.support.DefaultListableListBeanFactory.
And my configuration classes:
还有我的配置类:
1) AppConfig.
1) 应用配置。
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "kamienica")
public class AppConfig {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setContentType("UTF-8");
return viewResolver;
}
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
}
2) AppInitializer:
2)AppInitializer:
public class AppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(AppConfig.class);
ctx.setServletContext(container);
ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));
// added to handle local characters
FilterRegistration.Dynamic fr = container.addFilter("encodingFilter", new CharacterEncodingFilter());
fr.setInitParameter("encoding", "UTF-8");
fr.setInitParameter("forceEncoding", "true");
fr.addMappingForUrlPatterns(null, true, "/*");
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
And now the most important part:
现在最重要的部分:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("customUserDetailsService")
UserDetailsService userDetailsService;
//
// @Autowired
// CustomSuccessHandler customSuccessHandler;
//
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/index").permitAll().antMatchers("/Admin/**")
.access("hasRole('ADMIN')").antMatchers("/User/**").access("hasRole('ADMIN') or hasRole('USER')")
// .and().formLogin().loginPage("/login")
.and().formLogin()
// .loginPage("/login")
// .successHandler(customSuccessHandler)
// .usernameParameter("email").passwordParameter("password")
// .and().csrf()
// .and().exceptionHandling().accessDeniedPage("/Access_Denied")
;
}
}
My custom user service:
我的自定义用户服务:
@Component
@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
TenantService tenantService;
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
Tenant tenant = tenantService.loadByMail(email);
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority(tenant.getRole()));
return new org.springframework.security.core.userdetails.User(tenant.getEmail(), tenant.getPassword(), true,
true, true, true, authorities);
}
}
What am I doing wrong here?
我在这里做错了什么?
EDIT 1. I have modified the annotations in the files below but it did not solve the issue:
编辑 1. 我修改了以下文件中的注释,但没有解决问题:
@Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
TenantService tenantService;
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
Tenant tenant = tenantService.loadByMail(email);
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority(tenant.getRole()));
return new org.springframework.security.core.userdetails.User(tenant.getEmail(), tenant.getPassword(), true,
true, true, true, authorities);
}
}
And:
和:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsService userDetailsService;
//
// @Autowired
// CustomSuccessHandler customSuccessHandler;
//
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/index").permitAll().antMatchers("/Admin/**")
.access("hasRole('ADMIN')").antMatchers("/User/**").access("hasRole('ADMIN') or hasRole('USER')")
// .and().formLogin().loginPage("/login")
.and().formLogin()
// .loginPage("/login")
// .successHandler(customSuccessHandler)
// .usernameParameter("email").passwordParameter("password")
// .and().csrf()
// .and().exceptionHandling().accessDeniedPage("/Access_Denied")
;
}
}
EDIT 2: As per Selva's suggestion:
编辑 2:根据塞尔瓦的建议:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
CustomUserDetailsService customUserDetailsService;
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService);
auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/index").permitAll().antMatchers("/Admin/**")
.access("hasRole('ADMIN')").antMatchers("/User/**").access("hasRole('ADMIN') or hasRole('USER')")
.and().formLogin();
}
}
Unfortunately same result:
不幸的是同样的结果:
No qualifying bean of type [kamienica.service.CustomUserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
找不到类型为 [kamienica.service.CustomUserDetailsService] 的符合条件的依赖项:预计至少有 1 个符合此依赖项的自动装配候选者的 bean。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
回答by Sandhu Santhakumar
- Either use
@Component
or@Service
withCustomUserDetailsService
, not both. If you are using
@Service
, then use it like:@Service("userDetailsService")
Now get rid of the @Qualifier. Simply use:
@Autowired UserDetailsService userDetailsService;
- 使用
@Component
或@Service
withCustomUserDetailsService
,不能同时使用。 如果您正在使用
@Service
,则使用它:@Service("userDetailsService")
现在摆脱@Qualifier。只需使用:
@Autowired UserDetailsService userDetailsService;
回答by Maksim Ryabovol
I am beginner in Spring Boot and I met a similar problem but it is have been when i make tests for spring authentication. My case:
我是 Spring Boot 的初学者,我遇到了类似的问题,但是当我对 Spring 身份验证进行测试时就遇到了。我的情况:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class DefaultUserAuthenticationTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.build();
...
and received:
并收到:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'some.package.myClass.DefaultUserAuthenticationTest': Unsatisfied dependency expressed through field 'webApplicationContext'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.web.context.WebApplicationContext' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“some.package.myClass.DefaultUserAuthenticationTest”的bean时出错:通过字段“webApplicationContext”表达的不满意依赖;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有可用的“org.springframework.web.context.WebApplicationContext”类型的合格 bean:预计至少有 1 个 bean 有资格作为自动装配候选。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
When i did that:
当我这样做时:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration //added this annotation
public class DefaultUserAuthenticationTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
...
exception disappeared
异常消失
I finded solution here.
我在这里找到了解决方案。
回答by Saurabh Gupta
I am also facing the same issue and issue was that one of my security package my misspelled. all package was com.apps.test and for security it was com.app.test and it was getting failed. please check all your package initial as during component scanning it will fail if it i not same.
我也面临着同样的问题,问题是我拼错了我的一个安全包。所有包都是 com.apps.test,为了安全起见,它是 com.app.test 并且它失败了。请检查您的所有包的初始值,因为在组件扫描期间,如果它不相同,它将失败。