首页 > 解决方案 > 将数据库身份验证添加到 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();

}

我的用户表有一个电子邮件和密码列,将用作用户名/密码。

是否也可以通过某种方式使用它进行身份验证?我可以提供更多信息,但我不愿意只发布所有内容,并希望有人会为我写。

标签: javaspringspring-bootauthenticationspring-data-rest

解决方案


假设数据库表名是用户和权限。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());
                }
    }

推荐阅读