ITPub博客

首页 > 数据库 > 数据库开发技术 > SpringSecurity Session 管理

SpringSecurity Session 管理

原创 数据库开发技术 作者:DevXTalk 时间:2024-01-08 08:30:00 0 删除 编辑

SpringSecurity Session管理

  • SessionManagementConfigurer
  • SessionManagementFilter
  • SessionAuthenticationStrategy
  • SessionInformation
  • SessionRegistry
  • SessionInformationExpiredStrategy

SessionManagementConfigurer:主要是向HttpSecurity中注册有SessionManagementFilter过滤器

SessionManagementFilter:session认证

// session认证策略
private SessionAuthenticationStrategy sessionAuthenticationStrategy;

private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
// session认证策略,请求认证
this.sessionAuthenticationStrategy.onAuthentication(authentication, request, response);
chain.doFilter(request, response);
}

SessionAuthenticationStrategy:session的认证策略,多个实现

  1. RegisterSessionAuthenticationStrategy:通过SessionRegistry注册一个session
  2. ConcurrentSessionControlAuthenticationStrategy:session并发控制策略,一个用户可以有多少个Session。
  3. AbstractSessionFixationProtectionStrategy:每次访问都会更新sessionID,更新session的方法有两种,一种是不更改原来的session只设置sessionId,另外一种是创建一个新的session来替换原来的session。
@Override
public void ConcurrentSessionControlAuthenticationStrategy#onAuthentication(Authentication authentication, HttpServletRequest request,
HttpServletResponse response) {
int allowedSessions = getMaximumSessionsForThisUser(authentication);

List<SessionInformation> sessions = this.sessionRegistry.getAllSessions(authentication.getPrincipal(), false);
int sessionCount = sessions.size();
// 小于最大session允许数据,直接返回
if (sessionCount < allowedSessions) {
return;
}
// 等于最大允许数据,寻找对应的session返回
if (sessionCount == allowedSessions) {
HttpSession session = request.getSession(false);
if (session != null) {
for (SessionInformation si : sessions) {
if (si.getSessionId().equals(session.getId())) {
return;
}
}
}
}
// 超出session最大允许数量的处理。将超出的Session过期掉
allowableSessionsExceeded(sessions, allowedSessions, this.sessionRegistry);
}

SessionRegistry:用来注册SessionInformation信息。可以注册、获取、刷新、移除等等Session信息的操作

public interface SessionRegistry {
List<Object> getAllPrincipals();
List<SessionInformation> getAllSessions(Object principal, boolean includeExpiredSessions);
SessionInformation getSessionInformation(String sessionId);
void refreshLastRequest(String sessionId);
void registerNewSession(String sessionId, Object principal);
void removeSessionInformation(String sessionId);
}

欢迎加入 DevXTalk 的技术交流群,在这里你可以和大佬们一起交流分享技术,行业经验,提升自我。 结识新的业内朋友,扩大自己的圈子,当你想换工作的时候也许就能拿到不错的 offer 。总之期待你的加入...


「看完本文有收获?转发给更多的朋友吧」

「DevXTalk 不止于技术」

原文作者:DevXTalk;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2019-03-23

  • 博文量
    178
  • 访问量
    82575