限制同一用户同一时间只能一次登录系统(Acegi ConcurrentSessionFilter)

by 丑鑫鑫

如果系统是采用acegi security,你不需要另外编写额外的代码来满足这个需求,硬生生的写个Listener,Filter去监听或者拦截session,实现这个功能不叫重造轮子,应该叫做用别人的轮子重造轮胎 😉

采用Acegi 的系统限制同一用户同一时间只能一次登录系统步骤如下:

1.改写web.xml加入如下的语句

<listener>
<listener-class>org.acegisecurity.ui.session.HttpSessionEventPublisher</listener-class>
</listener>

这个监听器用来监听session生命期的事件

2.在acegi相关的spring bean配置文件加入:

<bean id=“authenticationManager” class=“org.acegisecurity.providers.ProviderManager”>
<property name=“providers”>
<!– your providers go here –>
</property>

<property name=“sessionController”><ref bean=“concurrentSessionController”/></property>
</bean>

<bean id=“concurrentSessionController” class=“org.acegisecurity.concurrent.ConcurrentSessionControllerImpl”>

<property name=“maximumSessions”><value>1</value></property>
<property name=“sessionRegistry”><ref local=“sessionRegistry”/></property>
</bean>

<bean id=“sessionRegistry” class=“org.acegisecurity.concurrent.SessionRegistryImpl”/>

执行的过程为用户couxinxin登录到系统,在另一台机器上couxinxin这个用户又登录到系统,那么前一个用户couxinxin的Session将被后者冲掉(踢掉)

搞定Over ! 🙂

必须要使用acegi1.0.6及其以后的版本,不然会报出
java.lang.IllegalArgumentException: Authentication.getDetails() required
这是版本1.0.5的bug
描述为:

If concurrent session control is used with an authentication provider which doesn’t copy the authentication details object to the successful authentication (e.g. CasAuthenticationProvider) then the check with the concurrent session controller on whether access is allowed takes place before the copyDetails method of AbstractAuthenticationManager is called. This isn’t a problem with classes which extend AbstractUserDetailsAuthenticationProvider, as it copies the authentication details object itself.

The copyDetails method should probably be pulled down into ProviderManager and called before checkAuthenticationAllowed() is called. This will ensure that the details object is available even if the provider doesn’t set it.

It’s also not clear that we really need an AbstractAuthenticationManager at all, given how little there is in there.

参见:http://jira.springframework.org/browse/SEC-618

ps: blogger 的xml排版有点难看,呵呵

留下评论

您的电子邮箱地址不会被公开。 必填项已用*标注