将 Spring Security 与 JPA 结合使用 [英] Use Spring Security with JPA
问题描述
我是 Spring 的新手.
I am new to Spring.
我们正在使用 spring 安全功能.数据库连接:JPA 的 eclipselink 实现.数据库:MySql
We are using spring security feature. Database connectivity: eclipselink implementation of JPA. Database: MySql
在使用spring security时,认证提供者的配置如下,-
While using spring security, Configuration of authentication provider is as follows,-
<authentication-provider>
<jdbc-user-service id="userDetailsService" data-source-ref="Datasource" />
</authentication-provider>
但是在 JPA 中我们没有定义数据源,我们使用 Persistence unit with provider jpa.PersistenceProvider.
But in JPA we do not define datasource, we use Persistence unit with provider jpa.PersistenceProvider.
那么我们如何配置身份验证提供程序以便使用 JPA 进行数据库连接?
So how do we configure authentication provider so as to use JPA for database connectivity?
data-source-ref 字段究竟应该包含什么才能使用数据库进行身份验证?
What exactly should data-source-ref field contain to use database for authentication?
提前致谢.
推荐答案
基本上你可能需要 自己实现UserDetailsService
.
Basically you probably need to implement UserDetailsService
yourself.
例如,您将拥有一个 User
实体,以及您的 UserDetailsService
实现将查找用户并将其转换为 UserDetails
对象(或者您的实体必须实现UserDetails
).
So you would for example have a User
entity, and your UserDetailsService
implementation would look up the user and convert it to a UserDetails
object (or your entity would have to implement UserDetails
).
示例实现:
public class MyUserDetailsService implements UserDetailsService{
private EntityManager entityManager;
@PersistenceContext
public void setEntityManager(EntityManager newEm){
this.entityManager = newEm;
}
public UserDetails loadUserByUsername(String username){
// assuming that you have a User class that implements UserDetails
return entityManager.createQuery("from User where username = :username", User.class)
.setParameter("username", username)
.getSingleResult();
}
}
然后将其添加到用户 spring-security.xml
<authentication-manager>
<authentication-provider user-service-ref="MyUserDetailsService" />
</authentication-manager>
这篇关于将 Spring Security 与 JPA 结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!