繁体   English   中英

Spring security 无法自动装配 UserDetailsS​​ervice

[英]Spring security Cant autowire UserDetailsService

我在尝试从数据库添加身份验证时遇到了困难。

这是错误日志:

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.UserDetailsS​​ervice kamienica.configuration.SecurityConfig.userDetailsS​​ervice; 嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:未找到类型为 [org.springframework.security.core.userdetails.UserDetailsS​​ervice] 的合格 bean 依赖项:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。 依赖注释:{@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=customUserDetailsS​​ervice)} 在 org.springframework.beans.factory.annotation .AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185) 在 org.springframework. :537) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) 在 org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302) 在 org.springframework .beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) 在 org.spr org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298) 在 org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) 在 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.refresh(AbstractApplication2Context.java) .springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403) 在 org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) 在 org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener) .java:106) 在 org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727) 在 org.apache.ca talina.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) 在 org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701) 在 org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717) 在 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)来源)由:org.springframework.beans.factory.BeanCreationException:无法自动装配字段:org.springframework.security.core.userdetails.UserDetailsS​​ervice kamienica.configuration.SecurityConfig.userDetailsS​​ervice; 嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:未找到类型为 [org.springframework.security.core.userdetails.UserDetailsS​​ervice] 的合格 bean 依赖项:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。 依赖注释:{@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=customUserDetailsS​​ervice)} 在 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.UserDetailsS​​ervice] 的合格 bean 依赖项:预计至少有 1 个 bean它有资格作为此依赖项的自动装配候选者。 依赖注释:{@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=customUserDetailsS​​ervice)} 在 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. :858) 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480) ... 28 更多

还有我的配置类:

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:

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("/");

    }

}

现在最重要的部分:

@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")
        ;
    }
}

我的自定义用户服务:

@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);
    }

}

我在这里做错了什么?

编辑 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);
    }

}

和:

@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")
        ;
    }
}

编辑 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();
    }
}

不幸的是同样的结果:

找不到类型为 [kamienica.service.CustomUserDetailsS​​ervice] 的符合条件的依赖项:预计至少有 1 个符合此依赖项的自动装配候选者的 bean。 依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}

  1. 使用@Component@ServiceCustomUserDetailsService ,而不是两者都使用。
  2. 如果您使用的是@Service ,那么请使用它:

    @Service("userDetailsService")

  3. 现在摆脱@Qualifier。 只需使用:

    @Autowired UserDetailsService userDetailsService;

我是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();
...

并收到:

org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为'some.package.myClass.DefaultUserAuthenticationTest'的bean时出错:通过字段'webApplicationContext'表示的不满意的依赖关系; 嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有类型为'org.springframework.web.context.WebApplicationContext'的限定bean可用:预期至少有1个bean可以作为autowire候选者。 依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}

当我这样做时:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration  //added this annotation
public class DefaultUserAuthenticationTest {

@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
...

异常消失了

在这里找到解决方案。

我也面临同样的问题,问题是我拼错了一个安全包。 所有包都是 com.apps.test,为了安全起见,它是 com.app.test 并且它失败了。 请检查您的所有包的初始值,因为在组件扫描期间,如果不相同,它将失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM