我需要知道哪些用户在网站上在线,因此我使用Spring Security提供的会话注册表(org.springframework.security.core.session.SessionRegistryImpl
)。这是我的Spring Security配置:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<beans:bean id="authenticationManager" class="my.package.security.AuthenticationManager" />
<http disable-url-rewriting="true" authentication-manager-ref="authenticationManager">
<intercept-url pattern="/login*" access="ROLE_ANONYMOUS" />
<intercept-url pattern="/*" access="ROLE_USER" />
<form-login login-processing-url="/authorize" login-page="/login" authentication-failure-url="/login-failed" />
<logout logout-url="/logout" logout-success-url="/login" />
<session-management session-authentication-strategy-ref="sas" invalid-session-url="/invalid-session" />
</http>
<beans:bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"/>
<beans:bean id="sas" class="org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy">
<beans:constructor-arg name="sessionRegistry" ref="sessionRegistry" />
<beans:property name="maximumSessions" value="1" />
</beans:bean>
</beans:beans>
如您所见,我正在使用自定义身份验证管理器(my.package.security.AuthenticationManager):
public class AuthenticationManager implements org.springframework.security.authentication.AuthenticationManager
{
@Autowired
UserJpaDao userDao;
public Authentication authenticate(Authentication authentication) throws AuthenticationException
{
User loggedInUser = null;
Collection<? extends GrantedAuthority> grantedAuthorities = null;
...
loggedInUser = loggedInUser = userDao.findByAlias(authentication.getName());
if(loggedInUser != null)
{
// Check password etc.
grantedAuthorities = loggedInUser.getAuthorities();
}
else
{
throw new BadCredentialsException("Unknown username");
}
return new UsernamePasswordAuthenticationToken(loggedInUser, authentication.getCredentials(), grantedAuthorities);
}
}
因此,sessionRegistry.getAllPrincipals()
会将User
s(List<Object>
“castable”的列表返回给List<User>
)。我想保留这个,因为它正是我所需要的。
现在,问题是User
是我自己的类,包含ManyToMany和OneToMany关系。出于这个原因,我在致电org.hibernate.LazyInitializationException
时获得sessionRegistry.getAllPrincipals()
。我想这是因为在Transaction中没有调用此方法,但是如何防止发生此异常呢?
谢谢。
答案 0 :(得分:1)
您不应存储用户对象,而应存储用户ID。