0

我想使用 EntityManager 通过 jdbcAuthentication 实现 Spring Security。但据我所知,唯一的选择是使用 Hibernate Datasource。

@Configuration
@EnableWebSecurity
@Import(value= {Application.class, ContextDatasource.class})
@ComponentScan(basePackages= {"org.rest.api.server.*"})
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired 
    private RestAuthEntryPoint authenticationEntryPoint;

    @Autowired
    private EntityManager entityManager;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
//      auth
//      .inMemoryAuthentication()
//      .withUser("test")
//      .password(passwordEncoder().encode("testpwd"))
//      .authorities("ROLE_USER");
//      auth.userDetailsService(myUserDetailsService);
        auth.jdbcAuthentication().dataSource(dataSource)
        auth.authenticationProvider(authenticationProvider());
    }
    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
//      authenticationProvider.setUserDetailsService(myUserDetailsService);
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        return authenticationProvider;
    }

这个问题有什么解决办法吗?

4

1 回答 1

1

您必须为身份验证和授权配置数据源 bean 和查询。

@Configuration
@PropertySource("classpath:db.properties")
public class AppConfig {

  @Autowired
  private Environment env;

  @Bean
  public DataSource getDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(env.getProperty("mysql.driver"));
    dataSource.setUrl(env.getProperty("mysql.jdbcUrl"));
    dataSource.setUsername(env.getProperty("mysql.username"));
    dataSource.setPassword(env.getProperty("mysql.password"));
    return dataSource;
  }
}

在 WebSecurityConfig 中,您必须放置数据源和查询。我假设您使用的是 HTTP 基本身份验证。您可以为每个角色添加授权。

@EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

      @Autowired
      private DataSource dataSource;

      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.jdbcAuthentication().dataSource(dataSource)
            .usersByUsernameQuery("select username, password, enabled"
                + " from users where username=?")
            .authoritiesByUsernameQuery("select username, authority "
                + "from authorities where username=?")
            .passwordEncoder(new BCryptPasswordEncoder());
      }

      @Override
      protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().anyRequest().hasAnyRole("ADMIN", "USER")
        .and()
        .httpBasic(); // Authenticate users with HTTP basic authentication
      }
    }
于 2018-09-09T04:14:01.047 回答