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主要包 ...
随机推荐
- ado.net 使用:ExecuteReader 无法获取输出参数
解决方法: 要获取到输出参数.需要连接关闭之后才行. 一般都是用using把打开数据库连接的reader包起来
- Windows下VSCode编译调试c/c++
参考链接: https://blog.csdn.net/c_duoduo/article/details/51615381 支持makefile编译: https://www.cnblogs.com ...
- 【归纳】正则表达式及Python中的正则库
正则表达式 正则表达式30分钟入门教程 runoob正则式教程 正则表达式练习题集(附答案) 元字符\b代表单词的分界处,在英文中指空格,标点符号或换行 例子:\bhi\b可以用来匹配hi这个单词,且 ...
- BootStrap顺序验证和指定字符个数发送请求
fields: { curPwd: { verbose: false, //代表验证按顺序验证.验证成功才会下一个(验证成功才会发最后一个remote远程验证) threshold: 6,//有6字符 ...
- WebService - [Debug] java.net.BindException: Can't assign requested address
Connected to the target VM, address: '127.0.0.1:57803', transport: 'socket' Exception in thread &quo ...
- Houdini SDF/Raymarching/等高曲面绘制
1 , SDF <1> union min(a,b) <2> intersect: max(a,b) <3> Substract a-b : if(b> ...
- Lua中的函数
[前言] Lua中的函数和C++中的函数的含义是一致的,Lua中的函数格式如下: function MyFunc(param) -- Do something end 在调用函数时,也需要将对应的参数 ...
- Android串口通信(Android Studio)
gilhub上已有开源项目: https://github.com/cepr/android-serialport-api 可以直接使用
- 翻译NYOJ
#include<iostream> #include<string.h> #include<stdio.h> using namespace std; ; int ...
- linux下安装redis并开机自启动
分享一个博客地址, 写的太好了, 满满的都是干货 ! https://www.cnblogs.com/renzhicai/p/7773080.html