基于java config的springSecurity--session并发控制
原作地址:http://blog.csdn.net/xiejx618/article/details/42892951
参考资料:spring-security-reference.pdf的Session Management.特别是Concurrency Control小节.
管理session可以做到:
a.跟踪活跃的session,统计在线人数,显示在线用户.
b.控制并发,即一个用户最多可以使用多少个session登录,比如设为1,结果就为,同一个时间里,第二处登录要么不能登录,要么使前一个登录失效.
1.注册自定义的SessionRegistry(通过它可以做到上面的a点)
- @Bean
- public SessionRegistry sessionRegistry(){
- return new SessionRegistryImpl();
- }
2.使用session并发管理,并注入上面自定义的SessionRegistry
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.authorizeRequests().anyRequest().authenticated()
- .and().formLogin().loginPage("/login").failureUrl("/login?error").usernameParameter("username").passwordParameter("password").permitAll()
- .and().logout().logoutUrl("/logout").logoutSuccessUrl("/login?logout").permitAll()
- .and().rememberMe().key("9D119EE5A2B7DAF6B4DC1EF871D0AC3C")
- .and().exceptionHandling().accessDeniedPage("/exception/403")
- .and().sessionManagement().maximumSessions(2).expiredUrl("/login?expired").sessionRegistry(sessionRegistry());
- }
3.监听session创建和销毁的HttpSessionListener.让spring security更新有关会话的生命周期,实现上创建的监听只使用销毁事件,至于session创建,security是调用org.springframework.security.core.session.SessionRegistry#registerNewSession
针对servlet管理的session,应使用org.springframework.security.web.session.HttpSessionEventPublisher,方法有多种:
a.重写org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer#enableHttpSessionEventPublisher
- public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
- @Override
- protected boolean enableHttpSessionEventPublisher() {
- return true;
- }
- }
b.在AbstractAnnotationConfigDispatcherServletInitializer的子类DispatcherServletInitializer添加
- @Override
- public void onStartup(ServletContext servletContext) throws ServletException {
- super.onStartup(servletContext);
- FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encoding-filter", CharacterEncodingFilter.class);
- encodingFilter.setInitParameter("encoding", "UTF-8");
- encodingFilter.setInitParameter("forceEncoding", "true");
- encodingFilter.setAsyncSupported(true);
- encodingFilter.addMappingForUrlPatterns(null, false, "/*");
- servletContext.addListener(new HttpSessionEventPublisher());
- }
使用springSession,直接向servletContext添加的session销毁监听是没用的,看springSession的文档http://docs.spring.io/spring-session/docs/current/reference/html5/#httpsession-httpsessionlistener,将org.springframework.security.web.session.HttpSessionEventPublisher注册成Bean就可以了.它的底层是对springSession的创建和销毁进行监听,不一样的.
还要注意的是,添加对HttpSessionListener的支持是从spring Session 1.1.0开始的,写这博文的时候,这版本还没出来.所以,以前的源码有问题.
- @Configuration
- @EnableRedisHttpSession
- @PropertySource("classpath:config.properties")
- public class HttpSessionConfig {
- @Resource
- private Environment env;
- @Bean
- public JedisConnectionFactory jedisConnectionFactory() {
- JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
- connectionFactory.setHostName(env.getProperty("redis.host"));
- connectionFactory.setPort(env.getProperty("redis.port",Integer.class));
- return connectionFactory;
- }
- @Bean
- public HttpSessionEventPublisher httpSessionEventPublisher() {
- return new HttpSessionEventPublisher();
- }
- }
4.在spring controller注入SessionRegistry,测试. 附加session的创建与销毁分析:
至于session的创建比较简单,认证成功后,security直接调用
- org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter#doFilter{
- sessionStrategy.onAuthentication(authResult, request, response);
- }
- org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy#onAuthentication{
- sessionRegistry.registerNewSession(request.getSession().getId(), uthentication.getPrincipal());
- }
session的销毁.没有特殊修改,org.springframework.security.web.authentication.logout.LogoutFilter#handlers只有一个元素org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler,如果主动logout,就会触发org.springframework.security.web.authentication.logout.LogoutFilter#doFilter,进而调用org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler#logout,从这个方法可以看出别人是怎么处理失效的session的
- public void logout(HttpServletRequest request, HttpServletResponse response,
- Authentication authentication) {
- Assert.notNull(request, "HttpServletRequest required");
- if (invalidateHttpSession) {
- HttpSession session = request.getSession(false);
- if (session != null) {
- logger.debug("Invalidating session: " + session.getId());
- session.invalidate();
- }
- }
- if (clearAuthentication) {
- SecurityContext context = SecurityContextHolder.getContext();
- context.setAuthentication(null);
- }
- SecurityContextHolder.clearContext();
- }
这里可以看到使session失效,调用SecurityContextHolder.getContext().setAuthentication(null),清理SecurityContext
spring security登出操作和session过期都会引起session被销毁.就会触发org.springframework.security.web.session.HttpSessionEventPublisher#sessionDestroyed事件.源码如下
- public void sessionDestroyed(HttpSessionEvent event) {
- HttpSessionDestroyedEvent e = new HttpSessionDestroyedEvent(event.getSession());
- Log log = LogFactory.getLog(LOGGER_NAME);
- if (log.isDebugEnabled()) {
- log.debug("Publishing event: " + e);
- }
- getContext(event.getSession().getServletContext()).publishEvent(e);
- }
getContext(event.getSession().getServletContext())得到的是Root ApplicationContext,所以要把SessionRegistryImpl Bean注册到Root ApplicationContext,这样SessionRegistryImpl的onApplicationEvent方法才能接收上面发布的HttpSessionDestroyedEvent事件.
- public void onApplicationEvent(SessionDestroyedEvent event) {
- String sessionId = event.getId();
- removeSessionInformation(sessionId);
- }
这里就看removeSessionInformation(sessionId);这里就会对SessionRegistryImpl相关信息进会更新.进而通过SessionRegistryImpl获得那些用户登录了,一个用户有多少个SessionInformation都进行了同步. 再来讨论getContext(event.getSession().getServletContext())
- ApplicationContext getContext(ServletContext servletContext) {
- return SecurityWebApplicationContextUtils.findRequiredWebApplicationContext(servletContext);
- }
- public static WebApplicationContext findRequiredWebApplicationContext(ServletContext servletContext) {
- WebApplicationContext wac = _findWebApplicationContext(servletContext);
- if (wac == null) {
- throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener registered?");
- }
- return wac;
- }
- private static WebApplicationContext _findWebApplicationContext(ServletContext sc) {
- //从下面调用看,得到的是Root ApplicationContext,而不是Servlet ApplicationContext
- WebApplicationContext wac = getWebApplicationContext(sc);
- if (wac == null) {
- Enumeration<String> attrNames = sc.getAttributeNames();
- while (attrNames.hasMoreElements()) {
- String attrName = attrNames.nextElement();
- Object attrValue = sc.getAttribute(attrName);
- if (attrValue instanceof WebApplicationContext) {
- if (wac != null) {
- throw new IllegalStateException("No unique WebApplicationContext found: more than one " +
- "DispatcherServlet registered with publishContext=true?");
- }
- wac = (WebApplicationContext) attrValue;
- }
- }
- }
- return wac;
- }
- public static WebApplicationContext getWebApplicationContext(ServletContext sc) {
- return getWebApplicationContext(sc, WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
- }

再假设得到的Servlet ApplicationContext,它还有parent(Root ApplicationContext),那么它也会通知Root ApplicationContext下监听SessionDestroyedEvent事件的Bean,(哈哈,但是没有那么多的如果);
但我还要如果用户就想在servlet注册SessionRegistryImpl,我觉得你可以继承HttpSessionEventPublisher,重写getContext方法了 针对于servlet容器的session,至于session过期,如果想测试,可以去改一下session的有效期短一点,然后等待观察.下面是我的测试web.xml全部内容
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app
- xmlns="http://xmlns.jcp.org/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
- metadata-complete="true"
- version="3.1">
- <session-config>
- <session-timeout>3</session-timeout>
- </session-config>
- </web-app>
对于用户主动关闭浏览器,服务端是没有马上触发sessionDestroyed的,等待session过期应该是大多数开发者的需求. 关于踢下线功能:使用org.springframework.security.core.session.SessionRegistry#getAllSessions就可以得到某个用户的所有SessionInformation,SessionInformation当然包括sessionId,剩下的问题就是根据sessionId获取session,再调用session.invalidate()就可以完成需求了.但是javax.servlet.http.HttpSessionContext#getSession已过期,并且因为安全原因没有替代方案,所以从servlet api2.1以后的版本,此路是不通的.
spring security提供了org.springframework.security.core.session.SessionInformation#expireNow,它只是标志了一下过期,直到下次用户请求被org.springframework.security.web.session.ConcurrentSessionFilter#doFilter拦截,
- HttpSession session = request.getSession(false);
- if (session != null) {
- SessionInformation info = sessionRegistry.getSessionInformation(session.getId());
- if (info != null) {
- if (info.isExpired()) {
- // Expired - abort processing
- doLogout(request, response);
- //其它代码忽略
- }
- }
- }
这里就会触发了用户登出.还有一种思路,session保存在redis,直接从redis删除某个session数据,详细看org.springframework.session.SessionRepository,不太推荐这么干. 还有SessionRegistryImpl实现的并发控制靠以下两个变量实现的用户在线列表,重启应用这两个实例肯定会销毁,
/** <principal:Object,SessionIdSet> */
private final ConcurrentMap<Object, Set<String>> principals = new ConcurrentHashMap<Object, Set<String>>();
/** <sessionId:Object,SessionInformation> */
private final Map<String, SessionInformation> sessionIds = new ConcurrentHashMap<String, SessionInformation>(); 既然分布式应用也会有问题,这时就要实现自己的SessionRegistry,将session的信息应保存到一个集中的地方进行管理.
基于java config的springSecurity--session并发控制的更多相关文章
- Spring Web工程web.xml零配置即使用Java Config + Annotation
摘要: 在Spring 3.0之前,我们工程中常用Bean都是通过XML形式的文件注解的,少了还可以,但是数量多,关系复杂到后期就很难维护了,所以在3.x之后Spring官方推荐使用Java Conf ...
- Java Config 注解
java config是指基于java配置的spring.传统的Spring一般都是基本xml配置的,后来spring3.0新增了许多java config的注解,特别是spring boot,基本都 ...
- 2510-Druid监控功能的深入使用与配置-基于SpringBoot-完全使用java config的形式
环境 springboot 1.5.9.RELEASE + JDK1.8 配置步骤 分两步,1 配置数据源 2 配置监控 直接上代码 1 配置数据源 package com.company.proje ...
- Spring IOC之基于JAVA的配置
基础内容:@Bean 和 @Configuration 在Spring中新的支持java配置的核心组件是 @Configuration注解的类和@Bean注解的方法. @Bean注解被用于表明一个方法 ...
- Spring Security4实例(Java config 版) —— Remember-Me
本文源码请看这里 相关文章: Spring Security4实例(Java config版)--ajax登录,自定义验证 Spring Security提供了两种remember-me的实现,一种是 ...
- Spring学习(15)--- 基于Java类的配置Bean 之 @Bean & @Scope 注解
默认@Bean是单例的,但可以使用@Scope注解来覆盖此如下: @Configuration public class MyConfiguration { @Bean @Scope("pr ...
- Spring Security4实例(Java config版)——ajax登录,自定义验证
本文源码请看这里 相关文章: Spring Security4实例(Java config 版) -- Remember-Me 首先添加起步依赖(如果不是springboot项目,自行切换为Sprin ...
- (4.1)Spring MVC执行原理和基于Java的配置过程
一.Spring MVC执行原理和基于Java配置的配置过程 (一)Spring MVC执行过程,大致为7步. 所有的请求都会经过Spring的一个单例的DispacherServlet. Dispa ...
- 基于Java的WebSocket推送
WebSocket的主动推送 关于消息推送,现在的解决方案如轮询.长连接或者短连接,当然还有其他的一些技术框架,有的是客户端直接去服务端拿数据. 其实推送推送主要讲的是一个推的概念,WebSocket ...
随机推荐
- 全自动链接克隆KVM虚拟机
virt-clone这个命令是基于全克隆的,也就是拷贝虚拟磁盘文件和虚拟配置文件来实现的完整克隆,速度慢,占用空间多 kvm软件包中并没有实现全自动链接克隆的命令或工具,只能手动实现,于是我决定写一个 ...
- Python中的序列
Python中有四种内建的数据结构,即列表.元组.字典.集合.其中字典和集合我会以后再写,现在先说列表和元组,它们两个和以前提到很多次的字符串, 其实都属于——序列. 一.列表(list): 1. l ...
- Hive 常用命令
1.hive模糊搜索表 show tables like '*name*'; 2.查看表结构信息 desc formatted table_name; desc table_name; 3.查看分 ...
- crt0.o
crt1.o, crti.o, crtbegin.o, crtend.o, crtn.o 等目标文件和daemon.o(由我们自己的C程序文件产生)链接成一个执行文件.前面这5个目标文件的作用分别是启 ...
- 关于LRU算法(转载)
原文地址: http://flychao88.iteye.com/blog/1977653 http://blog.csdn.net/cjfeii/article/details/47259519 ...
- IPC 进程间通信方式——管道
进程间通信概述 数据传输:一个进程需要将它的数据发送给另一个进程,发送的数据量在一个字节到几兆字节之间 共享数据:多个进程想要操作共享数据,一个进程对共享数据的修改,别的进程应该立刻看到. 通知时间: ...
- qt5---事件过滤器
- 【leetcode】1250. Check If It Is a Good Array
题目如下: Given an array nums of positive integers. Your task is to select some subset of nums, multiply ...
- C# 跨线程访问控件(MethodInvoker)
参考:https://www.cnblogs.com/lvdongjie/p/5428815.html .Net 通常禁止跨线程访问控件,设置Control.CheckForIllegalCrossT ...
- CSS currentColor 变量
㈠currentColor定义及理解 来自MDN的解释:currentColor代表了当前元素被应用上的color颜色值. 使用它可以将当前这个颜色值应用到其他属性上,或者嵌套元素的其他属性上. 你这 ...