基于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 ...
随机推荐
- Java语言基础(1)
1 计算机语言发展的分类 1)机器语言:由0,1组成(二进制),可以在计算机底层直接识别并执行(唯一). 2)汇编语言:由助记符组成,比机器语言简单.当执行的时候,把汇编语言转换为机器语言(0101) ...
- Balancing Act POJ - 1655 (树的重心)
Consider a tree T with N (1 <= N <= 20,000) nodes numbered 1...N. Deleting any node from the t ...
- java多线程的四种实现方式
主要有四种:继承Thread类.实现Runnable接口.实现Callable接口通过FutureTask包装器来创建Thread线程.使用ExecutorService.Callable.Futur ...
- pkg-config --libs libusb-1.0
pkg-config --libs libusb-1.0 pkg-config --libs libusb-1.0 pkg-config --libs libusb-1.0
- DevExpress ASP.NET v19.1版本亮点:发布全新的Gantt控件
行业领先的.NET界面控件DevExpress 发布了v19.1版本,本文将以系列文章的方式为大家介绍DevExpress ASP.NET Controls v19.1中新增的一些控件及增强的控件功能 ...
- dede 调取二级三级菜单栏目
{dede:channelartlist typeid='} <div class="cate-item"> <div class="cate-item ...
- [洛谷P2605] ZJOI2016 基站选址
问题描述 有N个村庄坐落在一条直线上,第i(i>1)个村庄距离第1个村庄的距离为Di.需要在这些村庄中建立不超过K个通讯基站,在第i个村庄建立基站的费用为Ci.如果在距离第i个村庄不超过Si的范 ...
- React native 之 图标库ECharts的使用
github地址:https://github.com/somonus/react-native-echarts 官网:https://www.echartsjs.com/zh/tutorial.ht ...
- getch和getchar的区别
造冰箱的大熊猫@cnblogs 2018/11/30 1.getc() 头文件:stdio.h 函数声明:int getc ( FILE * stream ); 功能: - 返回流(stream)当前 ...
- dp周训练 状态压缩
题目链接:题意:给你一个10*10的矩阵,每到一个格子中都要拿一个0-9的数值,求从矩阵左上方走到右下方且必须0-9都经过,拿的数值和最小是多少: #include <iostream> ...