gpt4 book ai didi

java - 使用EntityManager通过jdbcAuthentication实现Spring Security

转载 作者:行者123 更新时间:2023-12-02 10:50:10 24 4
gpt4 key购买 nike

我想使用 EntityManager 来通过 jdbcAuthentication 实现 Spring Security。但据我所知,唯一的选择是使用 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;
}

这个问题有解决办法吗?

最佳答案

您必须配置数据源 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
}
}

关于java - 使用EntityManager通过jdbcAuthentication实现Spring Security,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52238003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com