Мне нужно знать, какие пользователи находятся в сети на сайте, и по этой причине я использую реестр сеансов, предоставленный 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
с (List<Object>
"castable" в List<User>
).Я хотел бы сохранить это, потому что это именно то, что мне нужно.
Теперь проблема в том, что User
- это мой собственный класс и содержит отношения ManyToMany и OneToMany.По этой причине я получаю org.hibernate.LazyInitializationException
при звонке sessionRegistry.getAllPrincipals()
.Я предполагаю, что это происходит потому, что этот метод не вызывается внутри транзакции, но как я могу предотвратить возникновение этого исключения?
Спасибо.