Spring Security竞技场从数据库中读取我的登录凭据

时间:2014-03-31 18:22:21

标签: spring hibernate spring-mvc spring-security

我最近启动了一个spring项目,该项目利用spring security和hibernate来实现对项目的访问控制。 (可在此处获取申请的源代码:https://github.com/klebermo/webapp1)。

我的问题是系统没有从数据库中读取登录证书。我可以确保问题与数据库中的权限无关,因为Hibernate可以创建和更新表(事实上,我使用空数据库启动应用程序,并且所有表都是由系统创建的)。

有人可以发现我的代码有任何问题吗? (下面列出了SecurityConfig和HibernateConfig类,对于谁不希望在github存储库中搜索它们。)

SecurityConfig

@Configuration
@ComponentScan(value="org.webapp")
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource restDataSource;

    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .jdbcAuthentication()
            .dataSource(restDataSource)
            .usersByUsernameQuery(getUserQuery())
            .authoritiesByUsernameQuery(getAuthoritiesQuery());
    }

    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .disable()
            .authorizeRequests()
                .antMatchers("/spring/erro-login").permitAll()
                .antMatchers("/css/**", "/fonts/**", "/image/**", "/js/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/spring/index").permitAll()
                .loginProcessingUrl("/spring/login").permitAll()
                .usernameParameter("login")
                .passwordParameter("senha")
                .successHandler(new CustomAuthenticationSuccessHandler())
                .failureHandler(new CustomAuthenticationFailureHandler())
                .and()
            .logout()
                .logoutUrl("/spring/logout")
                .logoutSuccessUrl("/spring/index").permitAll();
    }

    private String getUserQuery() {
        return "SELECT login as username, senha as password "
                + "FROM usuario "
                + "WHERE login = ?";
    }

    private String getAuthoritiesQuery() {
        return "SELECT DISTINCT usuario.login as username, autorizacao.descricao as authority "
                + "FROM usuario, autorizacao_usuario, autorizacao "
                + "WHERE usuario.id = autorizacao_usuario.fk_usuario "
                + "AND autorizacao.id = autorizacao_usuario.fk_autorizacao "
                + "AND usuario.login = ? ";
    }

}

HibernateConfig

@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence.properties" })
@ComponentScan({ "org.webapp.persistence" })
public class HibernateConfig {

   @Autowired
   private Environment env;

   @Bean
   public LocalSessionFactoryBean sessionFactory() {
      LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
      sessionFactory.setDataSource(restDataSource());
      sessionFactory.setPackagesToScan(new String[] { "org.webapp.persistence.model" });
      sessionFactory.setHibernateProperties(hibernateProperties());

      return sessionFactory;
   }

   @Bean
   public DataSource restDataSource() {
      BasicDataSource dataSource = new BasicDataSource();
      dataSource.setDriverClassName(env.getProperty("jdbc.driverClassname"));
      dataSource.setUrl(env.getProperty("jdbc.url"));
      dataSource.setUsername(env.getProperty("jdbc.user"));
      dataSource.setPassword(env.getProperty("jdbc.pass"));

      return dataSource;
   }

   @Bean
   @Autowired
   public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
      HibernateTransactionManager txManager = new HibernateTransactionManager();
      txManager.setSessionFactory(sessionFactory);

      return txManager;
   }

   @Bean
   public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
      return new PersistenceExceptionTranslationPostProcessor();
   }

   Properties hibernateProperties() {
      return new Properties() {
         /**
         * 
         */
        private static final long serialVersionUID = 1L;

        {
            setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
            setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
            setProperty("hibernate.globally_quoted_identifiers", "true");
         }
      };
   }
}

2 个答案:

答案 0 :(得分:0)

从第一个@Autowired方法中删除configure(正如您在this指南中看到的那样,它不应该出现)

答案 1 :(得分:0)

虽然您已配置了Hiernate,但是为了检索用户数据库,您使用的是简单的JDBC数据源。

如果要基于Hibernate用户数据库配置Spring Web Security,可能必须为查询用户和用户角色创建dao,并通过实现CustomUserService创建自定义UserService

<强>参考:
http://www.javacodegeeks.com/2013/05/spring-mvc-security-with-mysql-and-hibernate.html