java - 将数据库身份验证添加到 Spring Data Rest 应用程序
问题描述
我正在使用带有 Thymeleaf 的 Spring Data REST 创建一个应用程序。
最初,我创建了模型、控制器、dao 和服务。一切正常。我现在正在尝试为我的应用程序添加安全性。现在我只专注于登录/注销。
我已经能够创建一个内存身份验证,如下所示:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("securityDataSource")
private DataSource securityDataSource;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// add users for in memory authentication
UserBuilder users = User.withDefaultPasswordEncoder();
auth.inMemoryAuthentication()
.withUser(users.username("paul").password("test123").roles("MEMBER", "ADMIN"))
.withUser(users.username("sandra").password("test123").roles("MEMBER", "ADMIN"))
.withUser(users.username("matthew").password("test123").roles("MEMBER"));
}
}
不过,我想将其更改为数据库身份验证。我很确定我可以创建一个 jdbc 连接并将我的配置方法更改为如下所示:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(securityDataSource);
}
我的问题是我已经通过我的 DAO 接口访问数据库。例如:
public interface UserRepository extends JpaRepository<User, Integer> {
// method to sort by last name
public List<User> findAllByOrderByLastNameAsc();
}
我的用户表有一个电子邮件和密码列,将用作用户名/密码。
是否也可以通过某种方式使用它进行身份验证?我可以提供更多信息,但我不愿意只发布所有内容,并希望有人会为我写。
解决方案
假设数据库表名是用户和权限。dataSource 在 application.yml 中配置。
@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());
}
}
推荐阅读
- unity3d - 我不能在 Unity 中的游戏对象前面有 UI 元素
- android - 找不到依赖模块中的活动文件
- javascript - 在 Vue.js 应用程序中包含 npm 包
- javascript - 需要在 React Native 中为 FlatList 将对象转换为数组
- shell - 在管道脚本 Jenkinsfile 中传递参数
- django - django - 通过 URL 传递不同的值
- python - 为什么gunicorn没有命令
- c# - 在 Windows 10 中运行 tlbimp.exe 命令不再生成新的 ADODB.dll
- reactjs - 我应该为反应网站部署 **.css.map/**.js.map 文件吗?
- flutter - Flutter 命令在 Windows 命令提示符下不起作用