在Hibernate中使用Spring Security中的jdbcAuthentication [英] Using jdbcAuthentication in Spring Security with Hibernate

查看:131
本文介绍了在Hibernate中使用Spring Security中的jdbcAuthentication的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚完成了基于 inMemoryAuthentication()的Spring应用程序,现在,在验证完所有工作都完美后,我想使用JDBC身份验证。 p>

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


  1. <基于本博客文章中介绍的代码,我们可以在 HibernateConfig 中找到它。
  2. 一个用于我数据库中的每个表(在当前状态下,我有三个:用户,角色和User_Role)
  3. 和一个UserService类,它实现 UserDetailsS​​ervice


我在网上阅读了一些文章,他们都使用SecurityConfig类的以下配置:

pre $ public $ SecurityConfig extends WebSecurityConfigurerAdapter @Autowired
私有DataSource数据源;

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



$ b $ p
$ b

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



$ @ $
@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)抛出异常{
http
.csrf()
.disable()
.authorizeRequests ()
.antMatchers(/ css / **,/ fonts / **,/ image / **,/ js / **)。permitAll()
。 anyRequest()。authenticated()
.and()
.formLogin()
.loginPage(/ spring / index)。permitAll()
.loginProcessingUrl(/ ())
.passwordParameter(senha)
.successHandler(new CustomAuthenticationSuccessHandler())
.failureHandler()新的CustomAuthenticationFailureHandler())
.and()
.logout()
.logoutUrl(/ spring / logout)
.logoutSuccessUrl(/ spring / index)。 permitAll();

$ b $ private String getUserQuery(){
returnSELECT login as username,senha as password
+FROM usuario
+WHERE登录=?;


private String getAuthoritiesQuery(){
returnSELECT 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 Authentication做了一些修改,但我仍然错过了将该类链接到我的Hibernate类的部分。



有人对如何做这件事有什么建议吗?

我的HibernateConfig是这样的

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

@Autowired
private环境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));

返回dataSource;


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

返回txManager;


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

属性hibernateProperties(){
返回新的属性(){
/ **
*
* /
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);
}
};
}
}


解决方案

好的,我解决了它。我需要做的就是在我的课程 SecurityConfig 中插入以下注释:

  @ComponentScan(value =org.webapp)

现在我可以自动装载我的<$这个类中的c $ c> DataSource

  @Autowired 
private DataSource restDataSource;

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


I just finished an Spring application which is based on the inMemoryAuthentication(), and now, after verified all are working perfectly, I want use the JDBC Authentication.

I have three kinds of classes to handle the connection to the database:

  1. HibernateConfig, based on the code presented in this blog post.

  2. DAO and Entity class, one for each table from my database (in this current state, I have three: User, Role and User_Role)

  3. And a UserService class, which implement UserDetailsService.

I read some articles on the Internet, and pratically all of them uses the following configuration for the class 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());
    }

What is an issue for me, since I don't have a Datasource class in my project. My current SecurityConfig is this:

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

}

As you can see, I already made some adaptations for use JDBC Authentication, but I am still missing the part where I link this class to my Hibernate class.

Someone have any suggestions in how to make this?

my HibernateConfig is this

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

解决方案

Ok, I solved it. All I needed to do was insert the following annotation in my class SecurityConfig:

@ComponentScan(value="org.webapp")

And now I can autowire my DataSource in this class

@Autowired
private DataSource restDataSource;

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

这篇关于在Hibernate中使用Spring Security中的jdbcAuthentication的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆