我想使用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;
}
这个问题有解决方案吗?
答案 0 :(得分: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
}
}