如何配置Spring-Security以访问数据库中的用户详细信息?

我对SpringSecurity感到困惑。有很多方法可以实现一个简单的东西,我把它们都混合在一起。

我的代码如下所示,但它会引发异常。如果我删除相关代码,应用程序将运行,我可以登录用户。如下所述,我将配置转换为基于 XML 的配置,但用户无法登录。UserDetailsServicein-memory

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 
com.myproj.config.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=userDetailsService)}

Caused by: org.springframework.beans.factory.BeanCreationException: Could not 
autowire field 

org.springframework.security.core.userdetails.UserDetailsService 
com.myproj.config.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=userDetailsService)}

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=userDetailsService)}

网.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <listener>
        <listener-class>org.apache.tiles.extras.complete.CompleteAutoloadTilesListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>proj</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
      <servlet-name>proj</servlet-name>
      <url-pattern>/</url-pattern>
    </servlet-mapping>



</web-app>

MvcWebApplicationInitializer

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;


public class MvcWebApplicationInitializer
    extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { SecurityConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

}

安全网站应用程序初始化程序

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SecurityWebApplicationInitializer
extends AbstractSecurityWebApplicationInitializer {

}

安全配置

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("userDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(
                passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/resources/**", "/", "/index", "/aboutus")
                .permitAll()
                .antMatchers("/profile/**")
                .hasRole("USER")
                .and()
                .formLogin().loginPage("/signin").failureUrl("/signin?error")
                .permitAll().and().logout().logoutUrl("/signout").permitAll();

    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception        
    {
        return super.authenticationManagerBean();
    }

}

会员服务简介

@Service("userDetailsService")
public class MemberServiceImpl implements UserDetailsService {

    @Autowired
    MemberRepository memberRepository;

    private List<GrantedAuthority> buildUserAuthority(String role) {
        Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
        setAuths.add(new SimpleGrantedAuthority(role));
        List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(
                setAuths);
        return result;
    }

    private User buildUserForAuthentication(Member member,
            List<GrantedAuthority> authorities) {
        return new User(member.getEmail(), member.getPassword(),
                member.isEnabled(), true, true, true, authorities);
    }

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        Member member = memberRepository.findByUserName(username);
        List<GrantedAuthority> authorities = buildUserAuthority("Role");
        return buildUserForAuthentication(member, authorities);
    }

}

更新 1

即使在从 SecurityConfig 中添加以下注释和方法后,也会引发相同的异常。authenticationManagerBean

    @EnableGlobalMethodSecurity(prePostEnabled = true)

更新 2

正如其中一个答案中建议的那样,我将其转换为基于XML的配置,当前代码如下所示;但是,当我提交登录表单时,它不会执行任何操作。

弹簧-安全.xml

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.0.xsd">



    <beans:import resource='login-service.xml' />
    <http auto-config="true" access-denied-page="/notFound.jsp"
        use-expressions="true">
        <intercept-url pattern="/" access="permitAll" />


        <form-login login-page="/signin" authentication-failure-url="/signin?error=1"
            default-target-url="/index" />
        <remember-me />
        <logout logout-success-url="/index.jsp" />
    </http>
    <authentication-manager>
        <authentication-provider>
            <!-- <user-service> <user name="admin" password="secret" authorities="ROLE_ADMIN"/> 
                <user name="user" password="secret" authorities="ROLE_USER"/> </user-service> -->
            <jdbc-user-service data-source-ref="dataSource"

                users-by-username-query="
              select username,password,enabled 
              from Member where username=?"

                authorities-by-username-query="
                      select username 
                      from Member where username = ?" />
        </authentication-provider>
    </authentication-manager>
</beans:beans>

登录服务.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">

    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost/testProject" />
    <property name="username" value="root" />
    <property name="password" value="" />
   </bean>

</beans>

答案 1

我想你忘了在安全配置类上添加此注释

@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("userDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(
                passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/resources/**", "/", "/index", "/aboutus")
                .permitAll().antMatchers("/profile/**").hasRole("USER").and()
                .formLogin().loginPage("/signin").failureUrl("/signin?error")
                .permitAll().and().logout().logoutUrl("/signout").permitAll();

    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

还有一件事我觉得这个豆子是不需要的

 @Bean
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }

请尝试这个,希望这将为你工作..

对于获取当前用户

public String getUsername() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        if (authentication == null)
            return null;
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        } else {
            return principal.toString();
        }
    }


    public User getCurrentUser() {
        if (overridenCurrentUser != null) {
            return overridenCurrentUser;
        }
        User user = userRepository.findByUsername(getUsername());

        if (user == null)
            return user;
    }

谢谢


答案 2

我认为这个问题可能是由于缺少注释。当尝试自动布线时,它无法找到合适的bean来自动布线。@ComponentScanuserDetailsServiceSecurityConfig

除了“mvc上下文”,“安全上下文”(您已经通过)等之外,Spring应用程序通常还有一个单独的“应用程序上下文”。SecurityConfig

我不确定穿上自己是否不起作用,但你可以试一试:@ComponentScanSecurityConfig

@Configuration
@ComponentScan("your_base_package_name_here")
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
}

将“your_base_package_name_here”替换为包含您的或类的包的名称。@Component@Service

如果这不起作用,请添加一个带有注释的新空类:@ComponentScan

@Configuration
@ComponentScan("your_base_package_name_here")
public class AppConfig {
    // Blank
}

资料来源:http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch06s02.html


推荐