Spring Security(五) —— 会话管理

一:基本介绍

当浏览器调用登录接口登录成功后,服务端会和浏览器之间建立一个会话(Session)浏览器在每次发送请求时都会携带一个Sessionld,服务端则根据这个Sessionld 来判断用户身份。当浏览器关闭后,服务端的Session并不会自动销毁,需要开发者手动在服务端调用Session销毁方法,或者等Session 过期时间到了自动销毁。在Spring Security中,与HttpSession相关的功能由SessionManagemenFiter和SessionAuthenticationStrategy接口来处理,SessionManagementFilter过滤器将Session相关操作委托给SessionAuthenticationStrategy接口去完成。

二:并发管理

会话并发管理就是指在当前系统中,同一个用户可以同时创建多少个会话,如果一台设备对应一个会话,那么也可以简单理解为同一个用户可以同时在多少台设备上进行登录。默认情况下,同一用户在多少台设备上登录并没有限制,不过开发者可以在Spring Security中对此进行配置。

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .sessionManagement()  // 开启会话管理
                .maximumSessions(1);  // 最大会话数为1
    }

可以看到,如果设置了会话数最大为1时,就不能在两台设备上同时登录了:


HttpSessionEventPublisher提供一个HttpSessionEventPublisher实例。Spring Security中通过一个Map集合来集护当前的HttpSession记录,进而实现会话的并发管理。当用户登录成功时,就向集合中添加一条HttpSession记录;当会话销毁时,就从集合中移除该HttpSession记录HttpSessionEventPublisher实现了HttpSessionListener接口,可以监听到HttpSession的创建和销毁事件,并将HttpSession的创建/销毁事件发布出去,这样,当有HttpSession销毁时,Spring Security就可以感知到该事件了。

三:会话被挤下线时的处理方案

上面已经展示了会话被异地登录挤下线的情况了,而在开发中,如果出现这种情况需要提示用户,也就是在用户发请求的时候给他返回session失效的json信息。而Spring Security提供了expiredSessionStrategy()方法供我们使用

public ConcurrencyControlConfigurer expiredSessionStrategy(
	SessionInformationExpiredStrategy expiredSessionStrategy) {
		SessionManagementConfigurer.this.expiredSessionStrategy = expiredSessionStrategy;
		return this;
}

下面是其类图:
在这里插入图片描述

其中默认的实现是ResponseBodySessionInformationExpiredStrategy,我们从其源码可以直观看出来,就是返回了一个提示

	private static final class ResponseBodySessionInformationExpiredStrategy
			implements SessionInformationExpiredStrategy {
		@Override
		public void onExpiredSessionDetected(SessionInformationExpiredEvent event)
				throws IOException {
			HttpServletResponse response = event.getResponse();
			response.getWriter().print(
					"This session has been expired (possibly due to multiple concurrent "
							+ "logins being attempted as the same user).");
			response.flushBuffer();
		}
	}

如果我们需要自定义提醒,那么就需要自己实现一个SessionInformationExpiredStrategy对象,而该接口只有一个方法,因此是个函数式接口,即可以使用Lambda表达式

public interface SessionInformationExpiredStrategy {
	// 当在ConcurrentSessionFilter中检测到过期会话时调用
	void onExpiredSessionDetected(SessionInformationExpiredEvent event)
			throws IOException, ServletException;
}

因此可以直接这么处理:

        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .sessionManagement()  // 开启会话管理
                .maximumSessions(1)  // 最大会话数为1
                .expiredSessionStrategy(event -> {
                    HttpServletResponse response = event.getResponse();
                    Map<String, Object> result = new HashMap<>();
                    result.put("msg", "当前会话已失效");
                    result.put("code", 500);
                    response.setContentType("application/json;charset=UTF-8");
                    String s = new ObjectMapper().writeValueAsString(result);
                    response.getWriter().println(s);
                });

在这里插入图片描述

当然这么写的话很不美观,因此我们可以将实现与配置分离:

public class CustomSessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        HttpServletResponse response = event.getResponse();
        Map<String, Object> result = new HashMap<>();
        result.put("msg", "当前会话已失效");
        result.put("code", 500);
        response.setContentType("application/json;charset=UTF-8");
        String s = new ObjectMapper().writeValueAsString(result);
        response.getWriter().println(s);
    }
}

然后在配置里传入:

        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .sessionManagement()  // 开启会话管理
                .maximumSessions(1)  // 最大会话数为1
                .expiredSessionStrategy(new CustomSessionInformationExpiredStrategy());

四:禁止再次登录

默认的效果是一种被“挤下线”的效果,后面登录的用户会把前面登录的用户“挤下线”。还有一种是禁止后来者登录,即一旦当前用户登录成功,后来者无法再次使用相同的用户登录,直到当前用户主动注销登录,这个实现起来其实特别简单,只要加一个配置就可以了:

        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .logout()
                .and()
                .sessionManagement()
                .maximumSessions(1)
                .expiredSessionStrategy(new CustomSessionInformationExpiredStrategy())
                .maxSessionsPreventsLogin(true);  // 禁止后来者登录

可见已经生效了
在这里插入图片描述

如果有兴趣了解更多相关内容,欢迎来我的个人网站看看:瞳孔的个人网站

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值