Spring Security系列教程20--会话管理之会话并发控制

简介: 前言现在我们已经掌握了如何防御会话固定攻击,以及在会话过期时的处理策略,但是这些都是针对单个HttpSession来说的,对于会话来说,我们还有另一种情况需要考虑:会话并发控制!那什么是会话并发控制呢?假如我想实现 “在我们的网站中,同一时刻只允许一个用户登录” 这样的效果,该怎么做?请各位带着以上的这些问题,跟着 一一哥 继续往下学习吧。一. 会话并发控制1. 会话并发控制首先我们来了解一下会话并发控制的概念。有时候出于安全的目的,我们可能会有这样的需求,就是规定在同一个系统中,只允许一个用户在一个终端上登录,这其实就是对会话的并发控制。2. 并发控制实现思路如果我们

前言

现在我们已经掌握了如何防御会话固定攻击,以及在会话过期时的处理策略,但是这些都是针对单个HttpSession来说的,对于会话来说,我们还有另一种情况需要考虑:会话并发控制!

那什么是会话并发控制呢?假如我想实现 “在我们的网站中,同一时刻只允许一个用户登录” 这样的效果,该怎么做?

请各位带着以上的这些问题,跟着 一一哥 继续往下学习吧。

一. 会话并发控制

1. 会话并发控制

首先我们来了解一下会话并发控制的概念。

有时候出于安全的目的,我们可能会有这样的需求,就是规定在同一个系统中,只允许一个用户在一个终端上登录,这其实就是对会话的并发控制。

2. 并发控制实现思路

如果我们要想上述目标,即同一个用户不能同时在两台设备上登录,我们有两种解决思路:

  • 后来的登录自动踢掉前面的登录,例如QQ。
  • 如果用户已经登录,则不允许后来者登录。

以上两种思路都能实现这个功能,具体使用哪一个,还要看我们具体的需求。在 Spring Security 框架中,这两种思路都很容易实现,一个配置就可以搞定。

3. 实现方案一:踢掉原有登录用户

我们可以在SecurityConfig配置类中,通过maximumSessions()方法来置单个用户允许同时在线的最大并发会话数,如果没有额外配置,重新登录的会话会踢掉旧的会话。

@EnableWebSecurity(debug=true)
publicclassSecurityConfigextendsWebSecurityConfigurerAdapter {
@Overrideprotectedvoidconfigure(HttpSecurityhttp) throwsException {
http.authorizeRequests()
                .antMatchers("/admin/**")
                .hasRole("ADMIN")
                .antMatchers("/user/**")
                .hasRole("USER")
                .antMatchers("/app/**")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .csrf()
                .disable()
                .formLogin()
                .permitAll()
                .and()
//进行会话管理                .sessionManagement()
//最大并发会话数,设置单个用户允许同时在线的最大会话数,如果没有额外配置,重新登录的会话会踢掉旧的会话.                .maximumSessions(1);
    }
@BeanpublicPasswordEncoderpasswordEncoder() {
returnNoOpPasswordEncoder.getInstance();
    }
}

maximumSessions: 表示最大并发会话数,设置单个用户允许同时在线的最大会话数,如果没有额外配置,重新登录的会话会踢掉旧的会话。这里配置最大会话数为 1,这样后面的登录就会自动踢掉前面的登录。

配置完成后,分别用 Chrome 和 Firefox 两个浏览器进行测试(或者使用 Chrome 中的多用户功能)。

  1. 我们先在Firefox 上访问 /user/hello 接口。
  2. 然后在Chrome 上访问 /user/hello 接口。

等我们在 Firefox 上再次访问 /user/hello 接口时,此时会看到如下提示:

以上信息表明第一个 session 已经过期,原因则是由于使用同一个用户进行并发登录。

4. 实现方案二:阻止新用户登录

如果我们已经有一个用户登录了,这时候这个相同的账号信息还想再次登录,我们可以阻止新用户登录,配置方式如下:

@EnableWebSecurity(debug=true)
publicclassSecurityConfigextendsWebSecurityConfigurerAdapter {
@Overrideprotectedvoidconfigure(HttpSecurityhttp) throwsException {
http.authorizeRequests()
                .antMatchers("/admin/**")
                .hasRole("ADMIN")
                .antMatchers("/user/**")
                .hasRole("USER")
                .antMatchers("/app/**")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .csrf()
                .disable()
                .formLogin()
                .permitAll()
                .and()
//进行会话管理                .sessionManagement()
//最大并发会话数,设置单个用户允许同时在线的最大会话数,如果没有额外配置,重新登录的会话会踢掉旧的会话.                .maximumSessions(1)
//当达到最大会话数时,阻止建立新会话,而不是踢掉旧的会话.默认为false                .maxSessionsPreventsLogin(true);
    }
/*** 监听session创建及销毁事件,来及时清理session的记录,以确保最新的session状态可以被及时感知到。*/@BeanpublicHttpSessionEventPublisherhttpSessionEventPublisher() {
returnnewHttpSessionEventPublisher();
    }
@BeanpublicPasswordEncoderpasswordEncoder() {
returnNoOpPasswordEncoder.getInstance();
    }
}

也就是说我们只需要添加 maxSessionsPreventsLogin(true)配置即可,此时一个浏览器登录成功后,另外一个浏览器就登录不了了,效果如下:

另外我们在上面的源码中,还配置了HttpSessionEventPublisher对象的创建。

注意:

我们之所以要创建HttpSessionEventPublisher这个Bean,是因为在 Spring Security 中,它可以通过监听session的创建及销毁事件,来及时的清理session记录。用户从不同的浏览器登录,都会有对应的session,当用户注销登录之后,session就会失效,但是默认的失效是通过调用 StandardSession#invalidate 方法来实现的。这一失效事件无法被 Spring 容器感知到,进而导致当前用户注销登录之后,Spring Security 没有及时清理会话信息表,以为用户还在线,进而导致用户无法重新登录进来。

为了解决这一问题,我们可以提供一个HttpSessionEventPublisher,这个类实现了HttpSessionListener 接口。在该 Bean 中,可以将 session 创建以及销毁的事件及时感知到,并且调用 Spring 中的事件机制将相关的创建和销毁事件发布出去,进而被 Spring Security 感知到,该类部分源码如下:

publicvoidsessionCreated(HttpSessionEventevent) {
HttpSessionCreatedEvente=newHttpSessionCreatedEvent(event.getSession());
Loglog=LogFactory.getLog(LOGGER_NAME);
if (log.isDebugEnabled()) {
log.debug("Publishing event: "+e);
    }
getContext(event.getSession().getServletContext()).publishEvent(e);
 }
/*** Handles the HttpSessionEvent by publishing a {@link HttpSessionDestroyedEvent} to* the application appContext.** @param event The HttpSessionEvent pass in by the container*/publicvoidsessionDestroyed(HttpSessionEventevent) {
HttpSessionDestroyedEvente=newHttpSessionDestroyedEvent(event.getSession());
Loglog=LogFactory.getLog(LOGGER_NAME);
if (log.isDebugEnabled()) {
log.debug("Publishing event: "+e);
    }
getContext(event.getSession().getServletContext()).publishEvent(e);
 }

这样我们就实现了会话的并发控制,代码也很简单。

二. 会话并发控制源码解析

两种会话并发控制方案我都已经带着各位实现了,那么底层的实现原理是什么样的呢? 我们一起来看看会话并发控制的源码吧。

1. 会话并发控制执行流程

在Spring Security中,对会话的并发控制也有特定的执行控制流程,该流程是在如下类中被触发执行的:

UsernamePasswordAuthenticationFilter-->AbstractAuthenticationProcessingFilter-->AbstractAuthenticationProcessingFilter#doFilter()

2. AbstractAuthenticationProcessingFilter#doFilter()源码

所以我们打开AbstractAuthenticationProcessingFilter过滤器来看看它的doFilter()方法是怎么定义的。

在这段源代码中我们可以看到,在调用完 attemptAuthentication方法执行完认证流程之后,接下来就会调用 sessionStrategy.onAuthentication 方法,这个方法就是用来处理 session 的并发问题的。

3. SessionAuthenticationStrategy接口

接着我们看看sessionStrategy对象所在类SessionAuthenticationStrategy的源码,内部定义了一个onAuthentication()方法。

publicinterfaceSessionAuthenticationStrategy {
/*** 当一个新的认证发生时,执行与session相关的功能。* */voidonAuthentication(Authenticationauthentication, HttpServletRequestrequest,
HttpServletResponseresponse) throwsSessionAuthenticationException;
}

我们看看该接口有哪些子类,发现该接口有多个子类,如下图所示:

其中默认的实现子类是NullAuthenticatedSessionStrategy,如下图所示:

4. ConcurrentSessionControlAuthenticationStrategy

但是当涉及到session的并发处理时,会由ConcurrentSessionControlAuthenticationStrategy这个子类来实现会话并发处理,核心方法如下:

publicvoidonAuthentication(Authenticationauthentication,
HttpServletRequestrequest, HttpServletResponseresponse) {
finalList<SessionInformation>sessions=sessionRegistry.getAllSessions(
authentication.getPrincipal(), false);
intsessionCount=sessions.size();
intallowedSessions=getMaximumSessionsForThisUser(authentication);
if (sessionCount<allowedSessions) {
// They haven't got too many login sessions running at presentreturn;
    }
if (allowedSessions==-1) {
// We permit unlimited loginsreturn;
    }
if (sessionCount==allowedSessions) {
HttpSessionsession=request.getSession(false);
if (session!=null) {
// Only permit it though if this request is associated with one of the// already registered sessionsfor (SessionInformationsi : sessions) {
if (si.getSessionId().equals(session.getId())) {
return;
     }
    }
   }
// If the session is null, a new one will be created by the parent class,// exceeding the allowed number    }
allowableSessionsExceeded(sessions, allowedSessions, sessionRegistry);
 }
protectedvoidallowableSessionsExceeded(List<SessionInformation>sessions,
intallowableSessions, SessionRegistryregistry)
throwsSessionAuthenticationException {
if (exceptionIfMaximumExceeded|| (sessions==null)) {
thrownewSessionAuthenticationException(messages.getMessage(
"ConcurrentSessionControlAuthenticationStrategy.exceededAllowed",
newObject[] {allowableSessions},
"Maximum sessions of {0} for this principal exceeded"));
    }
// Determine least recently used sessions, and mark them for invalidationsessions.sort(Comparator.comparing(SessionInformation::getLastRequest));
intmaximumSessionsExceededBy=sessions.size() -allowableSessions+1;
List<SessionInformation>sessionsToBeExpired=sessions.subList(0, maximumSessionsExceededBy);
for (SessionInformationsession: sessionsToBeExpired) {
session.expireNow();
    }
 }

这段核心代码主要含义如下:

  1. 首先调用 sessionRegistry.getAllSessions() 方法获取当前用户的所有 session信息,该方法在调用时会传递两个参数:一个是当前用户的 authentication,另一个参数 false 表示不包含已经过期的 session(在用户登录成功后,会将用户的 sessionid 存起来,其中 key 是用户的主体(principal),value 则是该主题对应的 sessionid 组成的一个集合)。
  2. 接下来计算当前用户已经有几个有效的 session,同时获取允许的 session 并发数。
  3. 如果当前 session 数(sessionCount)小于 session 并发数(allowedSessions),则不做任何处理;如果 allowedSessions 的值为 -1,表示对 session 数量不做任何限制。
  4. 如果当前的 session 数(sessionCount)等于 session 并发数(allowedSessions),那就先看看当前 session对象是否不为null,并且是否已经存在于 sessions 中了。如果已经存在了,则不做任何处理;如果当前 session 为 null,那么意味着将有一个新的 session 被创建出来,届时当前 session 数(sessionCount)就会超过 session 并发数(allowedSessions)。
  5. 如果前面的代码中都没能 return 掉,那么将进入策略判断方法 allowableSessionsExceeded 中。
  6. 在allowableSessionsExceeded 方法中,首先会有 exceptionIfMaximumExceeded 属性,这就是我们在 SecurityConfig 中配置的 maxSessionsPreventsLogin 的值,默认为 false。如果为 true,就直接抛出异常,那么这次登录就失败了;如果为 false,则对 sessions 按照请求时间进行排序,然后再使多余的 session 过期即可。

至此,壹哥 就跟大家讲解了会话并发控制的两种实现方案,并且给大家讲解了底层的实现源码,请各位照着我的文章进行实现和阅读,有不明白之处,请在评论区留言!

相关文章
|
JSON 安全 Java
什么是JWT?如何使用Spring Boot Security实现它?
什么是JWT?如何使用Spring Boot Security实现它?
2816 5
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
1783 3
|
存储 安全 Java
管理 Spring 微服务中的分布式会话
在微服务架构中,管理分布式会话是确保用户体验一致性和系统可扩展性的关键挑战。本文探讨了在 Spring 框架下实现分布式会话管理的多种方法,包括集中式会话存储和客户端会话存储(如 Cookie),并分析了它们的优缺点。同时,文章还涵盖了与分布式会话相关的安全考虑,如数据加密、令牌验证、安全 Cookie 政策以及服务间身份验证。此外,文中强调了分布式会话在提升系统可扩展性、增强可用性、实现数据一致性及优化资源利用方面的显著优势。通过合理选择会话管理策略,结合 Spring 提供的强大工具,开发人员可以在保证系统鲁棒性的同时,提供无缝的用户体验。
393 0
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
2222 5
|
Java Linux 网络安全
Linux云端服务器上部署Spring Boot应用的教程。
此流程涉及Linux命令行操作、系统服务管理及网络安全知识,需要管理员权限以进行配置和服务管理。务必在一个测试环境中验证所有步骤,确保一切配置正确无误后,再将应用部署到生产环境中。也可以使用如Ansible、Chef等配置管理工具来自动化部署过程,提升效率和可靠性。
1446 13
|
安全 Java 数据安全/隐私保护
使用Spring Security实现细粒度的权限控制
使用Spring Security实现细粒度的权限控制
|
安全 Java 数据库
Spring Boot 框架深入学习示例教程详解
本教程深入讲解Spring Boot框架,先介绍其基础概念与优势,如自动配置、独立运行等。通过搭建项目、配置数据库等步骤展示技术方案,并结合RESTful API开发实例帮助学习。内容涵盖环境搭建、核心组件应用(Spring MVC、Spring Data JPA、Spring Security)及示例项目——在线书店系统,助你掌握Spring Boot开发全流程。代码资源可从[链接](https://pan.quark.cn/s/14fcf913bae6)获取。
2323 3
|
消息中间件 Java Kafka
【Azure Kafka】使用Spring Cloud Stream Binder Kafka 发送并接收 Event Hub 消息及解决并发报错
reactor.core.publisher.Sinks$EmissionException: Spec. Rule 1.3 - onSubscribe, onNext, onError and onComplete signaled to a Subscriber MUST be signaled serially.
452 6