`

spring security中ajax超时处理

阅读更多

   spring security为我们的系统提供了方便的认证和授权操作。在系统中完成认证和授权后,一般页面页面上大多数是ajax和后台进行操作,那么这个时候可能就会面临session超时,ajax去访问后台的操作。或用户ajax匿名去访问一个受限的操作,此时应该如何进行处理。

   面对以上可能发生的2中情况,我们可能希望进行统一的处理,将此次ajax请求导向登录界面。

1. 当用户session超时后,使用ajax进行访问
    可以知道是SessionManagementFilter中的InvalidSessionStrategy进行处理的
2. 当用户是匿名用户访问,且session是新建的时候,访问了系统中的受限资源
    可以知道是ExceptionTranslationFilter中的handleSpringSecurityException进行处理
handleSpringSecurityException
        |- 匿名用户将使用 authenticationEntryPoint 进行处理
|- 非匿名用户使用 accessDeniedHandler 进行处理
具体的处理思路如下:
    1、拦截全局ajax请求
    2、重写InvalidSessionStrategy,增加ajax请求的处理
    3、重写AuthenticationEntryPoint增加ajax请求的处理
具体步骤:
一、拦截全局ajax请求
       判断后台返回的值是否是  session-time ,如果是则直接将该请求导向登录请求
$(document).ajaxComplete(function (event, obj) {
    var response = obj.responseText;
    if (response === 'session-timeout') {
        location.href = ctx + '/back/forward/login';
    }
});
二、当session超时后去,ajax请求访问后台,此时会被SessionManagementFilter进行拦截,由下图中可知,此时需要重写 InvalidSessionStrategy 类。

 
@Slf4j
public class SimpleAjaxAndRedirectInvalidSessionStrategy implements InvalidSessionStrategy {

	private final String destinationUrl;
	private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
	private boolean createNewSession = true;

	public SimpleAjaxAndRedirectInvalidSessionStrategy(String invalidSessionUrl) {
		Assert.isTrue(UrlUtils.isValidRedirectUrl(invalidSessionUrl), "url must start with '/' or with 'http(s)'");
		this.destinationUrl = invalidSessionUrl;
	}

	@Override
	public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		if (Objects.equals(request.getHeader("X-Requested-With"), "XMLHttpRequest")) {
			response.setContentType("text/html;charset=utf-8");
			response.setCharacterEncoding("utf-8");
			response.getWriter().write("session-timeout");
			response.getWriter().close();
		} else {
			log.debug("Starting new session (if required) and redirecting to '" + destinationUrl + "'");
			if (createNewSession) {
				request.getSession();
			}
			redirectStrategy.sendRedirect(request, response, destinationUrl);
		}
	}

	/**
	 * Determines whether a new session should be created before redirecting (to avoid
	 * possible looping issues where the same session ID is sent with the redirected
	 * request). Alternatively, ensure that the configured URL does not pass through the
	 * {@code SessionManagementFilter}.
	 *
	 * @param createNewSession defaults to {@code true}.
	 */
	public void setCreateNewSession(boolean createNewSession) {
		this.createNewSession = createNewSession;
	}
}
 注:一般ajax请求都有一个请求头X-Requeseted-With,且它的值是XMLHttpRequest
       如果涉及到跨域可能没有这个请求头,那么我们可以重写ajax请求加上一个自定义的请求头,只要能判断出ajax请求即可。
三、session是新建的,用户是匿名用户,此时ajax请求是访问一个受限的方法,由下图可知,此时需要重写 AuthenticationEntryPoint

public class HandleAnonyAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {

	/**
	 * @param loginFormUrl URL where the login page can be found. Should either be
	 *                     relative to the web-app context path (include a leading {@code /}) or an absolute
	 *                     URL.
	 */
	public HandleAnonyAuthenticationEntryPoint(String loginFormUrl) {
		super(loginFormUrl);
	}

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
		if (Objects.equals(request.getHeader("X-Requested-With"), "XMLHttpRequest")) {
			response.setContentType("text/html;charset=utf-8");
			response.setCharacterEncoding("utf-8");
			response.getWriter().write("session-timeout");
			response.getWriter().close();
		} else {
			super.commence(request, response, authException);
		}
	}
}
  四、spring secuirty 配置文件中增加这2个ajax 操作的处理

 
  • 大小: 84.1 KB
  • 大小: 200.5 KB
  • 大小: 45 KB
分享到:
评论

相关推荐

    spring security用户权限项目

    在这个项目中,这三者协同工作,Spring Security 负责后台的权限控制,Spring MVC 处理业务逻辑和数据交互,而 jQuery Easy-UI 则提供了用户友好的界面。理解这些知识点对于开发和维护这样一个用户权限管理项目至关...

    springsecurity前端素材.zip

    在本“springsecurity前端素材”中,我们有两个主要的文件夹:templates和static,它们分别代表了前端展示层的不同方面。 **templates** 文件夹通常包含了应用的HTML模板文件,这些文件被用于构建用户界面。在...

    spring security 参考手册中文版

    9.5 Spring Security中的访问控制(授权) 84 9.5.1安全和AOP建议 84 9.5.2安全对象和AbstractSecurityInterceptor 85 什么是配置属性? 85 RunAsManager 86 AfterInvocationManager 86 扩展安全对象模型 87 9.6本地...

    spring-978-1-7871-2951-1:Spring Security-第三版

    在Spring Security框架中,JavaScript的角色主要体现在前端交互和AJAX安全方面。Spring Security提供了基于HTTP头部的安全控制,可以通过JavaScript来实现与后端的交互,确保敏感数据的传输安全。例如,它支持JSON ...

    SpringSecurityTest

    【SpringSecurityTest】项目主要关注的是使用Spring Security框架进行安全测试和实现自定义的身份验证过期功能。Spring Security是Java领域中广泛使用的安全框架,它为应用程序提供了全面的安全管理解决方案,包括...

    spring boot+shiro+mybatis实现不同用户登录显示不同的权限菜单

    Spring Security可以作为Spring Boot的安全模块,但在这里我们选择了Apache Shiro来处理权限控制。 **Apache Shiro** Apache Shiro是一个轻量级的安全框架,它专注于认证、授权(权限)和会话管理。在本项目中,...

    SessionTimeOutAjaxRequest:当浏览器触发 Ajax 请求时,如何检测用户会话超时?

    [Spring Security 第六部分:Ajax 调用的会话超时处理] ( ) 安装 安装 使用 mvn clean install 编译项目 从 Maven 运行 Jetty:mvn jetty:run 用法 在连接到应用程序 默认用户是“ddoan/password”,但您可以在 ...

    dwr的例子 反向AJAX 实现时时提醒

    4. **安全(Security)**:DWR提供了一套机制来防止跨站脚本攻击(XSS)和其他类型的攻击,确保只有授权的方法可以被调用。 5. **实时更新(Live Updates)**:DWR支持实时更新,即服务器可以主动向客户端推送数据...

    springCloud

    Spring Cloud包含了多个子项目(针对分布式系统中涉及的多个不同开源产品),比如:Spring Cloud Config、Spring Cloud Netflix、Spring Cloud0 CloudFoundry、Spring Cloud AWS、Spring Cloud Security、Spring ...

    SpringBoot-Web-Mvc-Security:以Spring方式构建企业Java应用程序

    搜索和排序数据使用select2 ajax远程数据的分页结果发送带有附件的电子邮件模板多种语言的Web应用程序生成PDF和Excel文件使用Ajax以一种形式上传数据和文件建立和运行mvn packagejava -jar SpringBoot-0.0.1-...

    基于Springboot的酒店宾馆管理系统源码.zip

    Spring Security或Apache Shiro等安全框架可以用来实现身份验证和授权。 2. **房间管理**:包括房间类型、房间状态(如空闲、预订、占用)的维护,以及房间价格的设定,这些信息通常会存储在数据库中,Spring Data ...

    【ssm项目源码】在线点餐系统.zip

    8. **任务调度**:系统可能还需要处理定时任务,如订单超时处理、库存同步等,这可能用到Quartz或Spring的Task调度。 9. **单元测试与集成测试**:为了保证代码质量,项目中会有对应的测试代码,使用JUnit进行单元...

    上传下载文件(连接池)

    在Java Web开发中,常用的库有Apache Commons FileUpload和Spring MVC的MultipartFile接口,它们提供了处理文件流和临时存储上传文件的工具。 接下来,我们谈谈连接池。数据库连接池是一种管理数据库连接的机制,它...

    Room booking system

    Spring Security进行权限管理,确保系统安全。 3. 数据库存储:MySQL或PostgreSQL等关系型数据库用于存储房间信息、预订记录、用户数据等,使用JPA或MyBatis进行数据访问操作。 4. 消息队列:RabbitMQ或Kafka用于...

    structs框架(用户登录部分)

    Structs虽然不直接提供完整的安全解决方案,但可以与Spring Security、Apache Shiro等安全框架集成,实现用户认证与授权,防止SQL注入、XSS攻击等。 9. **模板引擎** Structs支持多种模板引擎,如FreeMarker、...

    OA.rar_OA管理员登录_java 管理系统

    在Java中,Spring Security或者Apache Shiro这样的安全框架可以用来实现这些功能,它们提供了一套完整的认证和授权机制,确保只有合法的管理员才能访问和管理数据。 员工登录界面则是系统的核心组成部分,员工可以...

    DWR推送技术大全 dwr推送聊天实例

    DWR可以集成Spring Security等框架进行会话管理和权限控制。 总的来说,DWR推送技术通过Comet实现了高效的服务器到客户端的数据推送,简化了实时Web应用的开发。结合提供的源码示例"j-jetty-dwr-comet-src",开发者...

    Ebay-like website for a college project.zip

    - 用户认证与授权,可能采用Spring Security或自定义的权限管理实现。 - 输入验证,防止SQL注入和跨站脚本攻击(XSS)。 - 加密敏感信息,如密码存储,通常会用到bcrypt或MD5算法。 6. **拍卖逻辑**: - 拍卖...

    javaweb-在线考试系统.zip

    4. **安全**:Spring Security或Apache Shiro实现用户认证和授权,防止未授权访问。MD5或更高级的加密算法确保用户密码安全。 5. **框架整合**:Spring Boot和Spring Cloud可以用于快速搭建和微服务化,提供统一的...

    JAVA上百实例源码以及开源项目

     数字证书:从文件中读取数字证书,生成文件输入流,输入文件为c:/mycert.cer,获取一个处理X.509证书的证书工厂…… Java+ajax写的登录实例 1个目标文件 内容索引:Java源码,初学实例,ajax,登录  一个Java+ajax写...

Global site tag (gtag.js) - Google Analytics