当使用spring security 的标签,如下,其中<sec:session-management>对应的SessionManagementFilter。从名字可以看出,这是一个管理Session的过滤器。这个过滤器会拦截每一个请求。然后判断用户有没有认证过。如果已经认证过,则执行Session认证策略。session 认证策略可配置。我们来看看这个过滤器的源代码,具体逻辑就直接在源码上标注。

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;

if (request.getAttribute(FILTER_APPLIED) != null) {
chain.doFilter(request, response);
return;
} request.setAttribute(FILTER_APPLIED, Boolean.TRUE); if (!securityContextRepository.containsContext(request)) {// 第一次访问,直接放行
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();//获取认证对象 if (authentication != null && !trustResolver.isAnonymous(authentication)) {//用户已经认证过
// The user has been authenticated during the current request, so call the
// session strategy
try {
sessionAuthenticationStrategy.onAuthentication(authentication,
request, response); //这里是session管理的关键,具体逻辑请看Session认证策略
}
catch (SessionAuthenticationException e) {
// The session strategy can reject the authentication
logger.debug(
"SessionAuthenticationStrategy rejected the authentication object",
e);
SecurityContextHolder.clearContext();
failureHandler.onAuthenticationFailure(request, response, e); return;
}
// Eagerly save the security context to make it available for any possible
// re-entrant
// requests which may occur before the current request completes.
// SEC-1396.
securityContextRepository.saveContext(SecurityContextHolder.getContext(),
request, response);
}
else {
// No security context or authentication present. Check for a session
// timeout
if (request.getRequestedSessionId() != null
&& !request.isRequestedSessionIdValid()) {
if (logger.isDebugEnabled()) {
logger.debug("Requested session ID "
+ request.getRequestedSessionId() + " is invalid.");
} if (invalidSessionStrategy != null) {
invalidSessionStrategy
.onInvalidSessionDetected(request, response);
return;
}
}
}
} chain.doFilter(request, response);
}

CompositeSessionAuthenticationStrategy.java:

public void onAuthentication(Authentication authentication,
HttpServletRequest request, HttpServletResponse response)
throws SessionAuthenticationException {
for (SessionAuthenticationStrategy delegate : delegateStrategies) {
if (logger.isDebugEnabled()) {
logger.debug("Delegating to " + delegate);
}
delegate.onAuthentication(authentication, request, response);
}
}
ConcurrentSessionControlAuthenticationStrategy.java
/**
* In addition to the steps from the superclass, the sessionRegistry will be updated
* with the new session information.
*/
public void onAuthentication(Authentication authentication,
HttpServletRequest request, HttpServletResponse response) { final List<SessionInformation> sessions = sessionRegistry.getAllSessions(
authentication.getPrincipal(), false); // 根据认证主体获取session int sessionCount = sessions.size();
int allowedSessions = getMaximumSessionsForThisUser(authentication); if (sessionCount < allowedSessions) {
// They haven't got too many login sessions running at present
return;
} if (allowedSessions == -1) {
// We permit unlimited logins
return;
} if (sessionCount == allowedSessions) {
HttpSession session = request.getSession(false); if (session != null) {
// Only permit it though if this request is associated with one of the
// already registered sessions
for (SessionInformation si : 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);
}
protected void allowableSessionsExceeded(List<SessionInformation> sessions,
int allowableSessions, SessionRegistry registry)
throws SessionAuthenticationException {
if (exceptionIfMaximumExceeded || (sessions == null)) {
throw new SessionAuthenticationException(messages.getMessage(
"ConcurrentSessionControlAuthenticationStrategy.exceededAllowed",
new Object[] { Integer.valueOf(allowableSessions) },
"Maximum sessions of {0} for this principal exceeded"));
} // Determine least recently used session, and mark it for invalidation
SessionInformation leastRecentlyUsed = null; for (SessionInformation session : sessions) {
if ((leastRecentlyUsed == null)
|| session.getLastRequest()
.before(leastRecentlyUsed.getLastRequest())) {
leastRecentlyUsed = session;
}
} leastRecentlyUsed.expireNow();
}
 
<sec:http>
  <sec:session-management/>
</sec:http>

Spring Security Session并发控制原理解析的更多相关文章

  1. Spring Security 解析(七) —— Spring Security Oauth2 源码解析

    Spring Security 解析(七) -- Spring Security Oauth2 源码解析   在学习Spring Cloud 时,遇到了授权服务oauth 相关内容时,总是一知半解,因 ...

  2. Spring Security 访问控制 源码解析

    上篇 Spring Security 登录校验 源码解析  分析了使用Spring Security时用户登录时验证并返回token过程,本篇分析下用户带token访问时,如何验证用户登录状态及权限问 ...

  3. Spring Security 入门(1-7)Spring Security - Session管理

    参考链接:https://xueliang.org/article/detail/20170302232815082 session 管理 Spring Security 通过 http 元素下的子元 ...

  4. Spring Security Session Time Out

    最近在用Spring Security做登录管理,登陆成功后,页面长时间无操作,超过session的有效期后,再次点击页面操作,页面无反应,需重新登录后才可正常使用系统. 为了优化用户体验,使得在se ...

  5. spring security控制session

    spring security控制session本文给你描述在spring security中如何控制http session.包括session超时.启用并发session以及其他高级安全配置. 创 ...

  6. Spring Security 5.0.x 参考手册 【翻译自官方GIT-2018.06.12】

    源码请移步至:https://github.com/aquariuspj/spring-security/tree/translator/docs/manual/src/docs/asciidoc 版 ...

  7. Spring Security 入门原理及实战

    目录 从一个Spring Security的例子开始 创建不受保护的应用 加入spring security 保护应用 关闭security.basic ,使用form表单页面登录 角色-资源 访问控 ...

  8. 44. Spring Security FAQ春季安全常见问题

    第44.1节,“一般问题” 第44.2节,“常见问题” 第44.3节,“春季安全架构问题” 第44.4节,“常见”如何“请求 44.1 General Questions 第44.1.1节,“Spri ...

  9. Spring Security的使用

    spring security使用目的:验证,授权,攻击防护. 原理:创建大量的filter和interceptor来进行请求的验证和拦截,以此来达到安全的效果. Spring Security主要包 ...

随机推荐

  1. unity发布的WebGL部署到IIS

    一.创建WebGL代码 在win7下,Unity3D中发布WebGL,然后部署到IIS,只要代码是对,关键是添加mime类型 二.为网站添加mime类型 .json text/json .unity3 ...

  2. 【原创】大数据基础之Oozie(2)使用

    命令行 $ oozie help 1 导出环境变量 $ export OOZIE_URL=http://oozie_server:11000/oozie 否则都需要增加 -oozie 参数,比如 $ ...

  3. cdh zookeeper 不断拒绝连接

    测试hiveserver2高可用的时候,需要登录zookeeper检查hiveserver2是否在zookeeper中注册 执行 zookeeper-client 不断的拒绝连接 -- ::, [my ...

  4. Vertx.vertx()初始框图和模块

    Vertx.vertx()实例 一.构造方法 1. VertxImpl构造方法 选择 transports protocol , default select 模型 if (options.getPr ...

  5. 金蝶k/3 K3密码对照破解源码

    金蝶k/3 K3密码对照破解源码 通过密码对照表进行密码破解 以下是源码: VERSION 5.00 Object = "{0ECD9B60-23AA-11D0-B351-00A0C9055 ...

  6. mq_receive

    NAME mq_receive - 从消息队列中获取消息 (REALTIME) SYNOPSIS #include <mqueue.h> ssize_t mq_receive(mqd_t ...

  7. xml格式转成json格式,使用Python

    import xml.etree.ElementTree root=xml.etree.ElementTree.parse('testXml.xml') book=root.findall('pers ...

  8. Hadoop| YARN| 计数器| 压缩| 调优

    1. 计数器应用 2. 数据清洗(ETL) 在运行核心业务MapReduce程序之前,往往要先对数据进行清洗,清理掉不符合用户要求的数据.清理的过程往往只需要运行Mapper程序,不需要运行Reduc ...

  9. http动词解释及规范

    GET:GET用于信息获取,而且应该是安全的和幂等的. 安全的意味着该操作用于获取信息而非修改信息,不管进行多少次操作,资源的状态都不会改变. 幂等的意味着对同一URL的多个请求应该返回同样的结果. ...

  10. Servlet(三):生命周期、常用方法、常见错误

    Servlet的生命周期:从第一次调用,到服务器关闭.如果在web.xml 中配置了load-on-startup则是从服务器开启到服务器关闭. 注意: * init方法是对Servlet进行初始化的 ...