我正在尝试将Spring Security与Hibernate集成。我是这两种技术的新手,所以我几乎肯定会在这里采取太多步骤,但我正处于我想从数据库中验证用户身份的地步。我认为这肯定是一个Spring Security问题的Hibernate问题,但我提到它给出一些上下文。以下是错误消息和代码。有谁能发现什么?
org.hibernate.HibernateException: No session currently bound to execution context
org.hibernate.context.ManagedSessionContext.currentSession(ManagedSessionContext.java:74)
org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:622)
com.vicinity.dao.hibernate.GenericHibernateDAO.findByCriteria(GenericHibernateDAO.java:99)
com.vicinity.dao.hibernate.HibernateUserDAO.getUserByLogin(HibernateUserDAO.java:35)
com.vicinity.service.PersistentUserManager.loadUserByUsername(PersistentUserManager.java:67)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:107)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
$Proxy31.loadUserByUsername(Unknown Source)
org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:83)
org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:125)
org.springframework.security.authentication.ProviderManager.doAuthentication(ProviderManager.java:121)
org.springframework.security.authentication.AbstractAuthenticationManager.authenticate(AbstractAuthenticationManager.java:49)
org.springframework.security.authentication.ProviderManager.doAuthentication(ProviderManager.java:139)
org.springframework.security.authentication.AbstractAuthenticationManager.authenticate(AbstractAuthenticationManager.java:49)
org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:98)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:356)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:106)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:356)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:356)
org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:108)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:356)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:150)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
配置DAO和事务管理:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="hibernateUserDAO" class="com.vicinity.dao.hibernate.HibernateUserDAO">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="userManagerTarget" class="com.vicinity.service.PersistentUserManager">
<property name="userDAO" ref="hibernateUserDAO" />
</bean>
<bean id="userManager" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref local="transactionManager" />
</property>
<property name="target">
<ref local="userManagerTarget" />
</property>
<property name="transactionAttributes">
<props>
<prop key="loadUserByUsername">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
这是实现UserDetailsService
的类,用于对用户进行身份验证。这会调用DAO,请参阅第userDAO.getUserByLogin(login);
行:
@Service("userManager")
@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public class PersistentUserManager implements UserManager, UserDetailsService {
@Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException, DataAccessException {
User user = userDAO.getUserByLogin(login);
if (null == user) {
logger.error("User with login: " + login + " not found in database");
throw new UsernameNotFoundException("user not found in database");
}
org.springframework.security.core.userdetails.User springUser;
springUser = new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), true,
true, true, true, new ArrayList<GrantedAuthority>());
return springUser;
}
}
这是从数据库中读取的DAO。请注意,我正在尝试利用'GenericDAO模式':
@Repository("userDAO")
public class HibernateUserDAO extends GenericHibernateDAO<User, Long> implements UserDAO {
public HibernateUserDAO() {
super(User.class);
}
@Override
public void createUser(User user) {
super.makePersistent(user);
}
public User getUserByLogin(String login) {
if (null == login) {
throw new IllegalArgumentException("You must provide a username if you want to get the user.");
}
List<User> users = findByCriteria(Restrictions.eq("login", login));
// TODO, might need to check here if there are more than one user with the same username
if(users == null || users.size() == 0) {
return null;
} else {
return users.get(0);
}
}
}
这是发生错误的类,行Criteria crit = getSessionFactory().getCurrentSession().createCriteria(getPersistentClass());
:
public abstract class GenericHibernateDAO<T, ID extends Serializable> implements GenericDAO<T, ID> {
private Class<T> persistentClass;
private SessionFactory sessionFactory;
@SuppressWarnings("unchecked")
protected List<T> findByCriteria(Criterion... criterion) {
Criteria crit = getSessionFactory().getCurrentSession().createCriteria(getPersistentClass());
for (Criterion c : criterion) {
crit.add(c);
}
return crit.list();
}
}
我的hibernate配置(hibernate.cfg.xml)中有以下内容可能是相关的:
<property name="current_session_context_class">org.hibernate.context.ManagedSessionContext</property>
答案 0 :(得分:2)
尝试使用此属性名称。
<property name="hibernate.current_session_context_class">
org.hibernate.context.ManagedSessionContext</property>
但是,最好配置spring来负责会话和事务管理。您可以查看this。
答案 1 :(得分:0)
您是否配置了交易管理?
org.springframework.orm.hibernate3.HibernateTransactionManager
和
org.springframework.transaction.interceptor.TransactionProxyFactoryBean
答案 2 :(得分:0)
我认为问题是由
引起的springUser = new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), true, true, true, true, new ArrayList<GrantedAuthority>());
Spring在DAO中使用了一个模板模式,所以当你执行getUserByLogin
会话是由Spring创建的,当你退出这个方法时,会话就会关闭。所以当你再次user.getLogin()
时没有附加会话,你得到错误。
尝试使用OpenSessionInViewFilter
....您可能需要在谷歌中搜索它(因为我自己也没有使用它,因此无法在此处显示代码)
另外你可以再做一件事,如果你从DAO本身返回springUser
(即在getUserByLogin
本身,那么它将使用相同的会话对象,它应该工作)
答案 3 :(得分:0)
我最近遇到了同样的错误,并且试图找出问题所在,试图找到问题。
就我而言,我使用的是OpenSessionInViewFilter
文件中配置的web.xml
,以及那里的Spring Security配置。
由于Spring Security和OpenSessionInViewFilter
都是过滤器,因此应用它们的顺序取决于它们在web.xml
文件中的显示顺序。
就我而言,我最初在Spring Security过滤器下面有OpenSessionInViewFilter
。一旦我交换了他们的位置(即将OpenSessionInViewFilter
置于Spring Security之上),一切正常!