如何使用 spring 数据 jpa 存储库以编程方式对用户进行身份验证?

How to authenticate user programmatically with spring data jpa repository?

我创建了带有 spring 数据审计的演示项目。

我有spring-security.xml个文件:

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-4.0.xsd">

    <authentication-manager>            
        <authentication-provider ref="userDao" />
    </authentication-manager>

</beans:beans>

引用spring数据jpa仓库userDao:

public interface UserDao extends CrudRepository<User, Long> {

    User findByUsernameAndPassword(String username, String password);
}

我希望 spring 数据 jpa 使用此方法来验证用户。

问题 2 是我需要以编程方式对用户进行身份验证。 我尝试使用 UserDetailsManager 但当我需要通过用户名和密码加载用户时它只有 loadByUsername 方法。

如何使用 UserDao.findByUsernameAndPassword 方法以编程方式对用户进行身份验证?

P.S。 User 实体实现 UserDetails 接口。

我假设您使用的是 Spring Security getting started page

中的基本配置

要以编程方式对用户进行身份验证,您需要将该用户置于安全上下文中。在您的特定情况下,它可能如下所示:

User user = userDao.findByUsernameAndPassword("username", "password");
SecurityContext ctx = SecurityContextHolder.createEmptyContext();
SecurityContextHolder.setContext(ctx);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user.getName(), user.getPassword(), AuthorityUtils.createAuthorityList("ROLE_USER"));
authentication.setDetails(user);
ctx.setAuthentication(authentication);