Spring Security实现禁止用户重复登陆的配置原理

网友投稿 505 2022-12-19


Spring Security实现禁止用户重复登陆的配置原理

这篇文章主要介绍了Spring Security实现禁止用户重复登陆的配置原理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

系统使用了Spring Security做权限管理,现在对于系统的用户,需要改动配置,实现无法多地登陆。

一、SpringMVC项目,配置如下:

首先在修改Security相关的XML,我这里是spring-security.xml,修改UsernamePasswordAuthenticationFilter相关Bean的构造配置

加入

新增sas的Bean及其相关配置

class="org.springframework.security.core.session.SessionRegistryImpl" />

加入ConcurrentSessionFilter相关Bean配置

class="org.springframework.security.web.session.ConcurrentSessionFilter">

class="org.springframework.security.web.session.SimpleRedirectSessionInformationExpiredStrategy">

二、SpringBoot项目

三、Bean配置说明

SessionAuthenticationStrategy:该接口中存在onAuthentication方法用于对新登录用户进行session相关的校验。

查看UsernamePasswordAuthenticationFilter及其父类代码,可以发现在doFilter中存在sessionStrategy.onAuthentication(authResult, request, response);方法

但UsernamePasswordAuthenticationFilter中的sessionStrategy对象默认为NullAuthenticatedSessionStrategy,即不对session进行相关验证。

如本文配置,建立id为sas的CompositeSessionAuthenticationStrategy的Bean对象。

CompositeSessionAuthenticationStrategy可以理解为一个托管类,托管所有实现SessionAuthenticationStrategy接口的对象,用来批量托管执行onAuthentication函数

这里CompositeSessionAuthenticationStrategy中注入了三个对象,关注ConcurrentSessionControlAuthenticatioQLlrEfwGnStrategy,它实现了对于session并发的控制

UsernamePasswordAuthenticationFilter的Bean中注入新配置的sas,用于替换原本的NullAuthenticatedSessionStrategy

ConcurrentSessionFilter的Bean用来验证session是否失效,并通过SimpleRedirectSessionInformationExpiredStrategy将失败访问进行跳转。

四、代码流程说明(这里模拟用户现在A处登录,随后用户在B处登录,之后A处再进行操作时会返回失败,提示重新登录)

1、用户在A处登录,UsernamePasswordAuthenticationFilter调用sessionStrategy.onAuthentication进行session验证

2、ConcurrentSessionControlAuthenticationStrategy中的onAuthentication开始进行session验证,服务器中保存了登录后的session

/**

* 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) {

//根据所登录的用户信息,查询相对应的现存session列表

final List sessions = sessionRegistry.getAllSessions(

authentication.getPrincipal(), false);

int sessionCount = sessions.size();

//获取session并发数量,对于XML中的maximumSessions

int allowedSessions = getMaximumSessionsForThisUser(authentication);

//判断现有session列表数量和并发控制数间的关系

//如果是首次登录,根据xml配置,这里应该是0<1,程序将会继续向下执行,

//最终执行到SessionRegistryImpl的registerNewSession进行新session的保存

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) {

//获取本次http请求的session

HttpSession session = request.getSession(false);

if (session != null) {

// Only permit it though if this request is associated with one of the

// already registered sessions

QLlrEfwG for (SessionInformation si : sessions) {

//循环已保存的session列表,判断本次http请求session是否已经保存

if (si.getSessionId().equals(session.getId())) {

//本次http请求是有效请求,返回执行下一个filter

return;

}

}

}

// If the session is null, a new one will be created by the parent class,

// exceeding the allowed number

}

//本次http请求为新请求,进入具体判断

allowableSessionsExceeded(sessions, allowedSessions, sessionRegistry);

}

/**

* Allows subclasses to customise behaviour when too many sessions are detected.

*

* @param sessions either null or all unexpired sessions associated with

* the principal

* @param allowableSessions the number of concurrent sessions the user is allowed to

* have

* @param registry an instance of the SessionRegistry for subclass use

*

*/

protected void allowableSessionsExceeded(List sessions,

int allowableSessions, SessionRegistry registry)

throws SessionAuthenticationException {

//根据exceptionIfMaximumExceeded判断是否要将新http请求拒绝

//exceptionIfMaximumExceeded也可以在XML中配置

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;

//若不拒绝新请求,遍历现存seesion列表

for (SessionInformation session : sessions) {

//获取上一次/已存的session信息

if ((leastRecentlyUsed == null)

|| session.getLastRequest()

.before(leastRecentlyUsed.getLastRequest())) {

leastRecentlyUsed = session;

}

}

//将上次session信息写为无效(欺骗)

leastRecentlyUsed.expireNow();

}

3、用户在B处登录,再次通过ConcurrentSessionControlAuthenticationStrategy的检查,将A处登录的session置于无效状态,并在session列表中添加本次session

4、用户在A处尝试进行其他操作,ConcurrentSessionFilter进行Session相关的验证,发现A处用户已经失效,提示重新登录

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)

throws IOException, ServletException {

HttpServletRequest request = (HttpServletRequest) req;

HttpServletResponse response = (HttpServletResponse) res;

//获取本次http请求的session

HttpSession session = request.getSession(false);

if (session != null) {

//从本地session关系表中取出本次http访问的具体session信息

SessionInformation info = sessionRegistry.getSessionInformation(session

.getId());

//如果存在信息,则继续执行

if (info != null) {

//判断session是否已经失效(这一步在本文4.2中被执行)

if (info.isExpired()) {

// Expired - abort processing

if (logger.isDebugEnabled()) {

logger.debug("Requested session ID "

+ request.getRequestedSessionId() + " has expired.");

}

//执行登出操作

doLogout(request, response);

//从XML配置中的redirectSessionInformationExpiredStrategy获取URL重定向信息,页面跳转到登录页面

this.sessionInformationExpiredStrategy.onExpiredSessionDetected(new SessionInformationExpiredEvent(info, request, response));

return;

}

else {

// Non-expired - update last request date/time

sessionRegistry.refreshLastRequest(info.getSessionId());

}

}

}

chain.doFilter(request, response);

}

5、A处用户只能再次登录,这时B处用户session将会失效重登,如此循环

class="org.springframework.security.core.session.SessionRegistryImpl" />

加入ConcurrentSessionFilter相关Bean配置

class="org.springframework.security.web.session.ConcurrentSessionFilter">

class="org.springframework.security.web.session.ConcurrentSessionFilter">

class="org.springframework.security.web.session.SimpleRedirectSessionInformationExpiredStrategy">

class="org.springframework.security.web.session.SimpleRedirectSessionInformationExpiredStrategy">

二、SpringBoot项目

三、Bean配置说明

SessionAuthenticationStrategy:该接口中存在onAuthentication方法用于对新登录用户进行session相关的校验。

查看UsernamePasswordAuthenticationFilter及其父类代码,可以发现在doFilter中存在sessionStrategy.onAuthentication(authResult, request, response);方法

但UsernamePasswordAuthenticationFilter中的sessionStrategy对象默认为NullAuthenticatedSessionStrategy,即不对session进行相关验证。

如本文配置,建立id为sas的CompositeSessionAuthenticationStrategy的Bean对象。

CompositeSessionAuthenticationStrategy可以理解为一个托管类,托管所有实现SessionAuthenticationStrategy接口的对象,用来批量托管执行onAuthentication函数

这里CompositeSessionAuthenticationStrategy中注入了三个对象,关注ConcurrentSessionControlAuthenticatioQLlrEfwGnStrategy,它实现了对于session并发的控制

UsernamePasswordAuthenticationFilter的Bean中注入新配置的sas,用于替换原本的NullAuthenticatedSessionStrategy

ConcurrentSessionFilter的Bean用来验证session是否失效,并通过SimpleRedirectSessionInformationExpiredStrategy将失败访问进行跳转。

四、代码流程说明(这里模拟用户现在A处登录,随后用户在B处登录,之后A处再进行操作时会返回失败,提示重新登录)

1、用户在A处登录,UsernamePasswordAuthenticationFilter调用sessionStrategy.onAuthentication进行session验证

2、ConcurrentSessionControlAuthenticationStrategy中的onAuthentication开始进行session验证,服务器中保存了登录后的session

/**

* 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) {

//根据所登录的用户信息,查询相对应的现存session列表

final List sessions = sessionRegistry.getAllSessions(

authentication.getPrincipal(), false);

int sessionCount = sessions.size();

//获取session并发数量,对于XML中的maximumSessions

int allowedSessions = getMaximumSessionsForThisUser(authentication);

//判断现有session列表数量和并发控制数间的关系

//如果是首次登录,根据xml配置,这里应该是0<1,程序将会继续向下执行,

//最终执行到SessionRegistryImpl的registerNewSession进行新session的保存

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) {

//获取本次http请求的session

HttpSession session = request.getSession(false);

if (session != null) {

// Only permit it though if this request is associated with one of the

// already registered sessions

QLlrEfwG for (SessionInformation si : sessions) {

//循环已保存的session列表,判断本次http请求session是否已经保存

if (si.getSessionId().equals(session.getId())) {

//本次http请求是有效请求,返回执行下一个filter

return;

}

}

}

// If the session is null, a new one will be created by the parent class,

// exceeding the allowed number

}

//本次http请求为新请求,进入具体判断

allowableSessionsExceeded(sessions, allowedSessions, sessionRegistry);

}

/**

* Allows subclasses to customise behaviour when too many sessions are detected.

*

* @param sessions either null or all unexpired sessions associated with

* the principal

* @param allowableSessions the number of concurrent sessions the user is allowed to

* have

* @param registry an instance of the SessionRegistry for subclass use

*

*/

protected void allowableSessionsExceeded(List sessions,

int allowableSessions, SessionRegistry registry)

throws SessionAuthenticationException {

//根据exceptionIfMaximumExceeded判断是否要将新http请求拒绝

//exceptionIfMaximumExceeded也可以在XML中配置

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;

//若不拒绝新请求,遍历现存seesion列表

for (SessionInformation session : sessions) {

//获取上一次/已存的session信息

if ((leastRecentlyUsed == null)

|| session.getLastRequest()

.before(leastRecentlyUsed.getLastRequest())) {

leastRecentlyUsed = session;

}

}

//将上次session信息写为无效(欺骗)

leastRecentlyUsed.expireNow();

}

3、用户在B处登录,再次通过ConcurrentSessionControlAuthenticationStrategy的检查,将A处登录的session置于无效状态,并在session列表中添加本次session

4、用户在A处尝试进行其他操作,ConcurrentSessionFilter进行Session相关的验证,发现A处用户已经失效,提示重新登录

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)

throws IOException, ServletException {

HttpServletRequest request = (HttpServletRequest) req;

HttpServletResponse response = (HttpServletResponse) res;

//获取本次http请求的session

HttpSession session = request.getSession(false);

if (session != null) {

//从本地session关系表中取出本次http访问的具体session信息

SessionInformation info = sessionRegistry.getSessionInformation(session

.getId());

//如果存在信息,则继续执行

if (info != null) {

//判断session是否已经失效(这一步在本文4.2中被执行)

if (info.isExpired()) {

// Expired - abort processing

if (logger.isDebugEnabled()) {

logger.debug("Requested session ID "

+ request.getRequestedSessionId() + " has expired.");

}

//执行登出操作

doLogout(request, response);

//从XML配置中的redirectSessionInformationExpiredStrategy获取URL重定向信息,页面跳转到登录页面

this.sessionInformationExpiredStrategy.onExpiredSessionDetected(new SessionInformationExpiredEvent(info, request, response));

return;

}

else {

// Non-expired - update last request date/time

sessionRegistry.refreshLastRequest(info.getSessionId());

}

}

}

chain.doFilter(request, response);

}

5、A处用户只能再次登录,这时B处用户session将会失效重登,如此循环


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:springboot + vue 实现递归生成多级菜单(实例代码)
下一篇:Spring Batch批处理框架使用解析
相关文章

 发表评论

暂时没有评论,来抢沙发吧~