Spring Security Session并发控制原理解析
当使用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并发控制原理解析的更多相关文章
- Spring Security 解析(七) —— Spring Security Oauth2 源码解析
Spring Security 解析(七) -- Spring Security Oauth2 源码解析 在学习Spring Cloud 时,遇到了授权服务oauth 相关内容时,总是一知半解,因 ...
- Spring Security 访问控制 源码解析
上篇 Spring Security 登录校验 源码解析 分析了使用Spring Security时用户登录时验证并返回token过程,本篇分析下用户带token访问时,如何验证用户登录状态及权限问 ...
- Spring Security 入门(1-7)Spring Security - Session管理
参考链接:https://xueliang.org/article/detail/20170302232815082 session 管理 Spring Security 通过 http 元素下的子元 ...
- Spring Security Session Time Out
最近在用Spring Security做登录管理,登陆成功后,页面长时间无操作,超过session的有效期后,再次点击页面操作,页面无反应,需重新登录后才可正常使用系统. 为了优化用户体验,使得在se ...
- spring security控制session
spring security控制session本文给你描述在spring security中如何控制http session.包括session超时.启用并发session以及其他高级安全配置. 创 ...
- Spring Security 5.0.x 参考手册 【翻译自官方GIT-2018.06.12】
源码请移步至:https://github.com/aquariuspj/spring-security/tree/translator/docs/manual/src/docs/asciidoc 版 ...
- Spring Security 入门原理及实战
目录 从一个Spring Security的例子开始 创建不受保护的应用 加入spring security 保护应用 关闭security.basic ,使用form表单页面登录 角色-资源 访问控 ...
- 44. Spring Security FAQ春季安全常见问题
第44.1节,“一般问题” 第44.2节,“常见问题” 第44.3节,“春季安全架构问题” 第44.4节,“常见”如何“请求 44.1 General Questions 第44.1.1节,“Spri ...
- Spring Security的使用
spring security使用目的:验证,授权,攻击防护. 原理:创建大量的filter和interceptor来进行请求的验证和拦截,以此来达到安全的效果. Spring Security主要包 ...
随机推荐
- ES6走一波 数组的扩展
Array flat 数组实例的扁平化方法(浏览器支持不佳) 建议使用 lodash的 flatten
- adb.exe 已停止工作解决办法
最近因为工作原因,接触了下Android Studio,在使用真机调试的时候碰到了adb.exe 已经停止工作的错误. 虽然网上有很多和我一样的教程,但是我觉的还是记录一下自己的情况比较好,毕竟每个人 ...
- 堆溢出学习笔记(linux)
本文主要是linux下堆的数据结构及堆调试.堆溢出利用的一些基础知识 首先,linux下堆的数据结构如下 /* This struct declaration is misleading (but a ...
- Windows Internals 笔记——CreateProcess
1.一个线程调用CreateProcess时,系统将创建一个进程内核对象,其初始使用计数为1.然后系统为新进程的主线程创建一个线程内核对象(使其计数为1). 2.CreateProcess在进程完全初 ...
- table行颜色设置
function renderingTable(obj){ $(obj).each(function(){ //设置奇数行颜色 $(this).find(" ...
- python实现简单的登录管理
import json,timeusername=[]userpasswd=[]def login_success_file(name): try: f=open(r"F:/login_su ...
- Spring注解式事务解析
#Spring注解式事务解析 增加一个Advisor 首先往Spring容器新增一个Advisor,BeanFactoryTransactionAttributeSourceAdvisor,它包含了T ...
- ionic2中使用videogular2实现m3u8文件播放
// 安装依赖 npm i videogular2 --save npm i hls.js --save // 在index.html中引入 <script src="assets/h ...
- fixed定位文本框引发的问题
<!-- 代码段1 --> <body> <!-- 可以滚动的区域 --> <main id="J_box"> <!-- 内容 ...
- Django跨域、cookie、session
前后台分离开发 1.前台页面运行在前台服务器上,负责页面的渲染(静态文件的加载)与跳转 2.后台代码运行在后台服务器上,负责数据的处理(提供数据请求的接口) 跨域 什么是跨域? 通常情况下,A网页访问 ...