2

我正在尝试将 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.cfg.xml)中有以下可能是相关的:

<property name="current_session_context_class">org.hibernate.context.ManagedSessionContext</property>
4

4 回答 4

2

尝试使用此属性名称。

<property name="hibernate.current_session_context_class">
       org.hibernate.context.ManagedSessionContext</property>

但是,最好将 spring 配置为负责会话和事务管理。你可以检查这个

于 2009-12-07T15:05:19.987 回答
0

我最近遇到了完全相同的错误,我把头撞在墙上试图找出问题所在。

就我而言,我使用了文件中的OpenSessionInViewFilter配置web.xml,以及那里的 Spring Security 配置。

由于 Spring Security 和OpenSessionInViewFilter都是过滤器,它们的应用顺序取决于它们在web.xml文件中出现的顺序。

就我而言,我最初有OpenSessionInViewFilter以下 Spring Security 过滤器。一旦我交换了他们的位置(即把OpenSessionInViewFilterSpring Security 放在上面),一切都很好!

于 2011-09-23T14:59:14.290 回答
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....您可能必须在谷歌中搜索它(因为我自己也没有使用它,因此无法在此处显示代码)

你还可以做一件事,如果你springUser从 DAO 本身返回(即getUserByLogin它本身,那么它将使用相同的会话对象并且它应该可以工作)

于 2009-12-07T15:11:02.597 回答
0

您是否配置了事务管理?

org.springframework.orm.hibernate3.HibernateTransactionManager

org.springframework.transaction.interceptor.TransactionProxyFactoryBean
于 2009-12-07T14:50:14.697 回答