spring security,如何使用户的所有会话到期

时间:2016-02-08 18:21:38

标签: spring spring-security weakhashmap

我必须在Spring Security 3.2.5-RELEASE中解决以下场景,其中Spring Core 4.1.2-RELEASE应用程序在wildfly 8.1上运行Java 1.7。

  1. 用户' bob'登录
  2. 和管理员删除' bob'
  3. 如果' bob'退出,他无法再次登录,但他当前的会话仍然有效。
  4. 我想踢' bob'出

    //this doesn't work
    for (final SessionInformation session :    sessionRegistry.getAllSessions(user, true)) {
             session.expireNow();
    }
    

2 个答案:

答案 0 :(得分:2)

  1. 将应用程序事件侦听器添加到跟踪HttpSessionCreatedEventHttpSessionDestroyedEvent并将其注册为ApplicationListener,并将SessionId的缓存维护为HttoSession。
  2. (可选)添加您自己的ApplicationEvent类AskToExpireSessionEvent -
  3. 用户管理服务中的
  4. 将依赖关系添加到SessionRegistryApplicationEventPublisher,以便您可以列出当前活动的用户会话,并找到对用户有效的用户会话(因为可能有很多)你正在寻找ie' bob'
  5. 删除用户为其每个会话发送AskToExpireSessionEvent时。
  6. 使用弱引用HashMap跟踪会话
  7. 用户服务:

         @Service
         public class UserServiceImpl implements UserService {
    
          /** {@link SessionRegistry} does not exists in unit tests */
          @Autowired(required = false)
          private Set<SessionRegistry> sessionRegistries;
    
    
          @Autowired
          private ApplicationEventPublisher publisher;
    
    
         /**
          * destroys all active sessions.
          * @return <code>true</code> if any session was invalidated^
          * @throws IllegalArgumentException
          */
          @Override
          public boolean invalidateUserByUserName(final String userName) {
                  if(null == StringUtils.trimToNull(userName)) {
                          throw new IllegalArgumentException("userName must not be null or empty");
                  }
                  boolean expieredAtLeastOneSession = false;
                  for (final SessionRegistry sessionRegistry : safe(sessionRegistries)) {
                          findPrincipal: for (final Object principal : sessionRegistry.getAllPrincipals()) {
                                  if(principal instanceof IAuthenticatedUser) {
                                          final IAuthenticatedUser user = (IAuthenticatedUser) principal;
                                          if(userName.equals(user.getUsername())) {
                                                  for (final SessionInformation session : sessionRegistry.getAllSessions(user, true)) {
                                                          session.expireNow();
                                                          sessionRegistry.removeSessionInformation(session.getSessionId());
                                                          publisher.publishEvent(AskToExpireSessionEvent.of(session.getSessionId()));
                                                          expieredAtLeastOneSession = true;
                                                  }
                                                  break findPrincipal;
                                          }
                                  } else {
                                          logger.warn("encountered a session for a none user object {} while invalidating '{}' " , principal, userName);
                                  }
                          }
                  }
                  return expieredAtLeastOneSession;
          }
    
         }
    

    申请活动:

         import org.springframework.context.ApplicationEvent;
    
         public class AskToExpireSessionEvent extends ApplicationEvent {
    
                 private static final long serialVersionUID = -1915691753338712193L;
    
                 public AskToExpireSessionEvent(final Object source) {
                         super(source);
                 }
    
                 @Override
                 public String getSource() {
                         return (String)super.getSource();
                 }
    
    
                 public static AskToExpireSessionEvent of(final String sessionId) {
                         return new AskToExpireSessionEvent(sessionId);
                 }
         }
    

    http会话缓存监听器:

         import java.util.Map;
         import java.util.WeakHashMap;
    
         import javax.servlet.http.HttpSession;
    
         import org.slf4j.Logger;
         import org.slf4j.LoggerFactory;
         import org.springframework.beans.factory.annotation.Autowired;
         import org.springframework.context.ApplicationListener;
         import org.springframework.security.web.session.HttpSessionCreatedEvent;
         import org.springframework.security.web.session.HttpSessionDestroyedEvent;
         import org.springframework.stereotype.Component;
    
         import com.cb4.base.service.event.AskToExpireSessionEvent;
    
    
         @Component
         public class HttpSessionCachingListener {
    
                 private static final Logger logger = LoggerFactory.getLogger(HttpSessionCachingListener.class);
    
                 private final Map<String, HttpSession> sessionCache = new WeakHashMap<>();
    
                 void onHttpSessionCreatedEvent(final HttpSessionCreatedEvent event){
                         if (event != null && event.getSession() != null && event.getSession().getId() != null) {
                                 sessionCache.put(event.getSession().getId(), event.getSession());
                         }
                 }
    
                 void onHttpSessionDestroyedEvent(final HttpSessionDestroyedEvent event){
                         if (event != null && event.getSession() != null && event.getSession().getId() != null){
                                 sessionCache.remove(event.getSession().getId());
                         }
                 }
    
                 public void timeOutSession(final String sessionId){
                         if(sessionId != null){
                                 final HttpSession httpSession = sessionCache.get(sessionId);
                                 if(null != httpSession){
                                         logger.debug("invalidating session {} in 1 second", sessionId);
                                         httpSession.setMaxInactiveInterval(1);
                                 }
                         }
                 }
    
                 @Component
                 static class HttpSessionCreatedLisener implements ApplicationListener<HttpSessionCreatedEvent> {
    
                         @Autowired
                         HttpSessionCachingListener parent;
    
                         @Override
                         public void onApplicationEvent(final HttpSessionCreatedEvent event) {
                                 parent.onHttpSessionCreatedEvent(event);
                         }
                 }
    
                 @Component
                 static class HttpSessionDestroyedLisener implements ApplicationListener<HttpSessionDestroyedEvent> {
    
                         @Autowired
                         HttpSessionCachingListener parent;
    
                         @Override
                         public void onApplicationEvent(final HttpSessionDestroyedEvent event) {
                                 parent.onHttpSessionDestroyedEvent(event);
                         }
                 }
    
                 @Component
                 static class AskToTimeOutSessionLisener implements ApplicationListener<AskToExpireSessionEvent> {
    
                         @Autowired
                         HttpSessionCachingListener parent;
    
                         @Override
                         public void onApplicationEvent(final AskToExpireSessionEvent event) {
                                 if(event != null){
                                         parent.timeOutSession(event.getSource());
                                 }
                         }
                 }
    
         }
    

答案 1 :(得分:0)

使用java config在您的类中添加以下代码,扩展 WebSecurityConfigurerAdapter

      @Bean
public SessionRegistry sessionRegistry( ) {
    SessionRegistry sessionRegistry = new SessionRegistryImpl( );
    return sessionRegistry;
}

@Bean
public RegisterSessionAuthenticationStrategy registerSessionAuthStr( ) {
    return new RegisterSessionAuthenticationStrategy( sessionRegistry( ) );
}

并在 configure(HttpSecurity http)方法中添加以下内容:

    http.sessionManagement( ).maximumSessions( -1 ).sessionRegistry( sessionRegistry( ) );
    http.sessionManagement( ).sessionFixation( ).migrateSession( )
            .sessionAuthenticationStrategy( registerSessionAuthStr( ) );

另外,在自定义身份验证bean中设置 registerSessionAuthenticationStratergy ,如下所示:

    usernamePasswordAuthenticationFilter
            .setSessionAuthenticationStrategy( registerSessionAuthStr( ) );

注意:在自定义身份验证bean中设置 registerSessionAuthenticationStratergy 会导致填充原则列表,因此当您尝试从sessionRegistry获取所有prinicipals列表时( sessionRegistry.getAllPrinicpals()< / em>),列表不为空。