在Spring Security和Hibernate中使用jdbcAuthentication

问题描述

好的,我解决了。我需要做的就是在我的班级中插入以下注释SecurityConfig

@ComponentScan(value="org.webapp")

现在我可以DataSource在这堂课中自动接线

@Autowired
private DataSource restDataSource;

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

解决方法

我刚刚完成了一个基于的Spring应用程序inMemoryAuthentication(),现在,在验证所有应用程序正常运行之后,我想使用JDBC身份验证。

我有三种类来处理与数据库的连接:

  1. HibernateConfig,基于此博客文章中提供的代码。

  2. DAO和Entity类,数据库中的每个表一个(在当前状态下,我有三个:User,Role和User_Role)

  3. 还有一个UserService类,该类实现UserDetailsService

我在Internet上阅读了一些文章,并且实际上它们都对SecurityConfig类使用以下配置:

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

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

对我来说,这是个问题,因为我的项目中没有Datasource类。我当前的SecurityConfig是这样的:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .disable()
            .authorizeRequests()
                .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 = ? ";
    }

}

如您所见,我已经对使用JDBC身份验证进行了一些修改,但是我仍然缺少将此类链接到Hibernate类的部分。

有人对此有何建议?

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

相关文章

猜你在找的编程问答相关文章

怎样才能让 Git“忘记”一个被跟踪但现在在 .gitignore 中的文件?
Python 中的metaclasses是什么?
如何在 Linux 上查找包含特定文本的所有文件?
如何从异步调用返回响应
如何在一个表达式中合并两个字典(取字典的并集)?
HTTP 中的 POST 和 PUT 有什么区别?
使用 Git 将最近的提交移动到新分支
在 JavaScript 比较中应该使用哪个等于运算符 (== vs ===)?