当前位置: 移动技术网 > IT编程>开发语言>Java > Spring Security 自动踢掉前一个登录用户的实现代码

Spring Security 自动踢掉前一个登录用户的实现代码

2020年05月13日  | 移动技术网IT编程  | 我要评论

沈定成简历,坏蛋是怎样炼成的续,搜刮

登录成功后,自动踢掉前一个登录用户,松哥第一次见到这个功能,就是在扣扣里边见到的,当时觉得挺好玩的。

自己做开发后,也遇到过一模一样的需求,正好最近的 spring security 系列正在连载,就结合 spring security 来和大家聊一聊这个功能如何实现。

本文是本系列的第十三篇,阅读前面文章有助于更好的理解本文:

  1. 挖一个大坑,spring security 开搞!
  2. 松哥手把手带你入门 spring security,别再问密码怎么解密了
  3. 手把手教你定制 spring security 中的表单登录
  4. spring security 做前后端分离,咱就别做页面跳转了!统统 json 交互
  5. spring security 中的授权操作原来这么简单
  6. spring security 如何将用户数据存入数据库?
  7. spring security+spring data jpa 强强联手,安全管理只有更简单!
  8. spring boot + spring security 实现自动登录功能
  9. spring boot 自动登录,安全风险要怎么控制?
  10. 在微服务项目中,spring security 比 shiro 强在哪?
  11. springsecurity 自定义认证逻辑的两种方式(高级玩法)
  12. spring security 中如何快速查看登录用户 ip 地址等信息?

1.需求分析

在同一个系统中,我们可能只允许一个用户在一个终端上登录,一般来说这可能是出于安全方面的考虑,但是也有一些情况是出于业务上的考虑,松哥之前遇到的需求就是业务原因要求一个用户只能在一个设备上登录。

要实现一个用户不可以同时在两台设备上登录,我们有两种思路:

  • 后来的登录自动踢掉前面的登录,就像大家在扣扣中看到的效果。
  • 如果用户已经登录,则不允许后来者登录。

这种思路都能实现这个功能,具体使用哪一个,还要看我们具体的需求。

在 spring security 中,这两种都很好实现,一个配置就可以搞定。

2.具体实现

2.1 踢掉已经登录用户

想要用新的登录踢掉旧的登录,我们只需要将最大会话数设置为 1 即可,配置如下:

@override
protected void configure(httpsecurity http) throws exception {
 http.authorizerequests()
   .anyrequest().authenticated()
   .and()
   .formlogin()
   .loginpage("/login.html")
   .permitall()
   .and()
   .csrf().disable()
   .sessionmanagement()
   .maximumsessions(1);
}

maximumsessions 表示配置最大会话数为 1,这样后面的登录就会自动踢掉前面的登录。这里其他的配置都是我们前面文章讲过的,我就不再重复介绍,文末可以下载案例完整代码。

配置完成后,分别用 chrome 和 firefox 两个浏览器进行测试(或者使用 chrome 中的多用户功能)。

  • chrome 上登录成功后,访问 /hello 接口。
  • firefox 上登录成功后,访问 /hello 接口。
  • 在 chrome 上再次访问 /hello 接口,此时会看到如下提示:

this session has been expired (possibly due to multiple concurrent logins being attempted as the same user).

可以看到,这里说这个 session 已经过期,原因则是由于使用同一个用户进行并发登录。

2.2 禁止新的登录

如果相同的用户已经登录了,你不想踢掉他,而是想禁止新的登录操作,那也好办,配置方式如下:

@override
protected void configure(httpsecurity http) throws exception {
 http.authorizerequests()
   .anyrequest().authenticated()
   .and()
   .formlogin()
   .loginpage("/login.html")
   .permitall()
   .and()
   .csrf().disable()
   .sessionmanagement()
   .maximumsessions(1)
   .maxsessionspreventslogin(true);
}

添加 maxsessionspreventslogin 配置即可。此时一个浏览器登录成功后,另外一个浏览器就登录不了了。

是不是很简单?

不过还没完,我们还需要再提供一个 bean:

@bean
httpsessioneventpublisher httpsessioneventpublisher() {
 return new httpsessioneventpublisher();
}

为什么要加这个 bean 呢?因为在 spring security 中,它是通过监听 session 的销毁事件,来及时的清理 session 的记录。用户从不同的浏览器登录后,都会有对应的 session,当用户注销登录之后,session 就会失效,但是默认的失效是通过调用 standardsession#invalidate 方法来实现的,这一个失效事件无法被 spring 容器感知到,进而导致当用户注销登录之后,spring security 没有及时清理会话信息表,以为用户还在线,进而导致用户无法重新登录进来(小伙伴们可以自行尝试不添加上面的 bean,然后让用户注销登录之后再重新登录)。

为了解决这一问题,我们提供一个 httpsessioneventpublisher ,这个类实现了 httpsessionlistener 接口,在该 bean 中,可以将 session 创建以及销毁的事件及时感知到,并且调用 spring 中的事件机制将相关的创建和销毁事件发布出去,进而被 spring security 感知到,该类部分源码如下:

public void sessioncreated(httpsessionevent event) {
	httpsessioncreatedevent e = new httpsessioncreatedevent(event.getsession());
	getcontext(event.getsession().getservletcontext()).publishevent(e);
}
public void sessiondestroyed(httpsessionevent event) {
	httpsessiondestroyedevent e = new httpsessiondestroyedevent(event.getsession());
	getcontext(event.getsession().getservletcontext()).publishevent(e);
}

ok,虽然多了一个配置,但是依然很简单!

3.实现原理

上面这个功能,在 spring security 中是怎么实现的呢?我们来稍微分析一下源码。

首先我们知道,在用户登录的过程中,会经过 usernamepasswordauthenticationfilter(参考: spring security 登录流程),而 usernamepasswordauthenticationfilter 中过滤方法的调用是在 abstractauthenticationprocessingfilter 中触发的,我们来看下 abstractauthenticationprocessingfilter#dofilter 方法的调用:

public void dofilter(servletrequest req, servletresponse res, filterchain chain)
		throws ioexception, servletexception {
	httpservletrequest request = (httpservletrequest) req;
	httpservletresponse response = (httpservletresponse) res;
	if (!requiresauthentication(request, response)) {
		chain.dofilter(request, response);
		return;
	}
	authentication authresult;
	try {
		authresult = attemptauthentication(request, response);
		if (authresult == null) {
			return;
		}
		sessionstrategy.onauthentication(authresult, request, response);
	}
	catch (internalauthenticationserviceexception failed) {
		unsuccessfulauthentication(request, response, failed);
		return;
	}
	catch (authenticationexception failed) {
		unsuccessfulauthentication(request, response, failed);
		return;
	}
	// authentication success
	if (continuechainbeforesuccessfulauthentication) {
		chain.dofilter(request, response);
	}
	successfulauthentication(request, response, chain, authresult);

在这段代码中,我们可以看到,调用 attemptauthentication 方法走完认证流程之后,回来之后,接下来就是调用 sessionstrategy.onauthentication 方法,这个方法就是用来处理 session 的并发问题的。具体在:

public class concurrentsessioncontrolauthenticationstrategy implements
		messagesourceaware, sessionauthenticationstrategy {
	public void onauthentication(authentication authentication,
			httpservletrequest request, httpservletresponse response) {

		final list<sessioninformation> sessions = sessionregistry.getallsessions(
				authentication.getprincipal(), false);

		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[] {allowablesessions},
					"maximum sessions of {0} for this principal exceeded"));
		}

		// determine least recently used sessions, and mark them for invalidation
		sessions.sort(comparator.comparing(sessioninformation::getlastrequest));
		int maximumsessionsexceededby = sessions.size() - allowablesessions + 1;
		list<sessioninformation> sessionstobeexpired = sessions.sublist(0, maximumsessionsexceededby);
		for (sessioninformation session: sessionstobeexpired) {
			session.expirenow();
		}
	}
}

这段核心代码我来给大家稍微解释下:

  • 首先调用 sessionregistry.getallsessions 方法获取当前用户的所有 session,该方法在调用时,传递两个参数,一个是当前用户的 authentication,另一个参数 false 表示不包含已经过期的 session(在用户登录成功后,会将用户的 sessionid 存起来,其中 key 是用户的主体(principal),value 则是该主题对应的 sessionid 组成的一个集合)。
  • 接下来计算出当前用户已经有几个有效 session 了,同时获取允许的 session 并发数。
  • 如果当前 session 数(sessioncount)小于 session 并发数(allowedsessions),则不做任何处理;如果 allowedsessions 的值为 -1,表示对 session 数量不做任何限制。
  • 如果当前 session 数(sessioncount)等于 session 并发数(allowedsessions),那就先看看当前 session 是否不为 null,并且已经存在于 sessions 中了,如果已经存在了,那都是自家人,不做任何处理;如果当前 session 为 null,那么意味着将有一个新的 session 被创建出来,届时当前 session 数(sessioncount)就会超过 session 并发数(allowedsessions)。
  • 如果前面的代码中都没能 return 掉,那么将进入策略判断方法 allowablesessionsexceeded 中。
  • allowablesessionsexceeded 方法中,首先会有 exceptionifmaximumexceeded 属性,这就是我们在 securityconfig 中配置的 maxsessionspreventslogin 的值,默认为 false,如果为 true,就直接抛出异常,那么这次登录就失败了(对应 2.2 小节的效果),如果为 false,则对 sessions 按照请求时间进行排序,然后再使多余的 session 过期即可(对应 2.1 小节的效果)。

4.小结

如此,两行简单的配置就实现了 spring security 中 session 的并发管理。是不是很简单?不过这里还有一个小小的坑,松哥将在下篇文章中继续和大家分析。

本文案例大家可以从 github 上下载:

到此这篇关于spring security 自动踢掉前一个登录用户的实现代码的文章就介绍到这了,更多相关spring security 踢掉登录用户内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网