Внедрите Spring Security с помощью jdbcAuthentication с использованием EntityManager - PullRequest
0 голосов
/ 08 сентября 2018

Я хочу реализовать Spring Security с помощью jdbcAuthentication с использованием EntityManager. Но, насколько я вижу, единственный вариант - использовать источник данных Hibernate.

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

Есть ли решение этой проблемы?

1 Ответ

0 голосов
/ 09 сентября 2018

Вы должны сконфигурировать компонент источника данных и запрос для аутентификации и авторизации.

@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
      }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...