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 操作的处理




 

spring security中ajax超时处理的更多相关文章

  1. [收藏]Spring Security中的ACL

    ACL即访问控制列表(Access Controller List),它是用来做细粒度权限控制所用的一种权限模型.对ACL最简单的描述就是两个业务员,每个人只能查看操作自己签的合同,而不能看到对方的合 ...

  2. Spring Security中html页面设置hasRole无效的问题

    Spring Security中html页面设置hasRole无效的问题 一.前言 学了几天的spring Security,偶然发现的hasRole和hasAnyAuthority的区别.当然,可能 ...

  3. Spring Security 中的过滤器

    本文基于 spring-security-core-5.1.1 和 tomcat-embed-core-9.0.12. Spring Security 的本质是一个过滤器链(filter chain) ...

  4. Spring Security 中的 Bcrypt

    最近在写用户管理相关的微服务,其中比较重要的问题是如何保存用户的密码,加盐哈希是一种常见的做法.知乎上有个问题大家可以先读一下: 加盐密码保存的最通用方法是? 对于每个用户的密码,都应该使用独一无二的 ...

  5. 浅谈使用spring security中的BCryptPasswordEncoder方法对密码进行加密与密码匹配

    浅谈使用springsecurity中的BCryptPasswordEncoder方法对密码进行加密(encode)与密码匹配(matches) spring security中的BCryptPass ...

  6. 看源码,重新审视Spring Security中的角色(roles)是怎么回事

    在网上看见不少的博客.技术文章,发现大家对于Spring Security中的角色(roles)存在较大的误解,最大的误解就是没有搞清楚其中角色和权限的差别(好多人在学习Spring Security ...

  7. 六:Spring Security 中使用 JWT

    Spring Security 中使用 JWT 1.无状态登录 1.1 什么是有状态? 1.2 什么是无状态 1.3 如何实现无状态 2.JWT 2.1 JWT数据格式 2.2 JWT交互流程 2.3 ...

  8. 五:Spring Security 中的角色继承问题

    Spring Security 中的角色继承问题 以前的写法 现在的写法 源码分析 SpringSecurity 在角色继承上有两种不同的写法,在 Spring Boot2.0.8(对应 Spring ...

  9. Spring Security中实现微信网页授权

    微信公众号提供了微信支付.微信优惠券.微信H5红包.微信红包封面等等促销工具来帮助我们的应用拉新保活.但是这些福利要想正确地发放到用户的手里就必须拿到用户特定的(微信应用)微信标识openid甚至是用 ...

随机推荐

  1. linq 集合按照多列进行distinct

    List<TaskBatch> sourceList = (from c in BatchCollecion                                         ...

  2. minio & gitlab runner

    Docker安装Minio存储服务器详解 # mkdir -p /data/minio # docker pull nexus3:8089/minio/minio # docker run -p 90 ...

  3. SpringBoot系列——附件管理:整合业务表单实现上传、回显、下载

    前言 日常开发中,大多数项目都会涉及到附件上传.回显.下载等功能,本文记录封装通用附件管理模块,并与业务模块进行整合实现上传.回显.下载 我们之前已经对文件上传下载有过记录,传送门:基于"f ...

  4. 什么是 baseline 和 benchmark

    baseline 一个算法被称为 baseline 算法说明这个比目前这个算法还差的已经不能接受了,方法有革命性的创新点可以挖掘,且存在巨大提升空间和超越benchmark的潜力,只是由于发展初期导致 ...

  5. use关键字在PHP中的几种用法

    在学习了和使用了这么多年的PHP之后,您知道use这个关键字在PHP中都有哪些用法吗?今天我们就来看一下它的三种常见用法. 1. 用于命名空间的别名引用 // 命名空间 include 'namesp ...

  6. 启动jemeter 报错相关解决方案

    1:当启动jemeter时报错"页面文件太小,无法完成操作" 如图: 是说明分配的内容不足,即可调整内存重启即可解决 1):打开:控制面板>系统和安全>系统 2):点击 ...

  7. 华为云计算IE面试笔记-云磁盘和普通磁盘的区别。

    1. 定义 云硬盘:一种虚拟块存储服务,主要为ECS和BMS提供块存储空间 普通磁盘:也称本地硬盘,指挂载在计算实例物理机上的本地硬盘 2. 性能 吞吐量具体情况具体分析.(若云磁盘用的SSD本地磁盘 ...

  8. 鸿蒙内核源码分析(特殊进程篇) | 龙生龙,凤生凤,老鼠生儿会打洞 | 百篇博客分析OpenHarmony源码 | v46.02

    百篇博客系列篇.本篇为: v46.xx 鸿蒙内核源码分析(特殊进程篇) | 龙生龙凤生凤老鼠生儿会打洞 | 51.c.h .o 进程管理相关篇为: v02.xx 鸿蒙内核源码分析(进程管理篇) | 谁 ...

  9. excel模板数据填充 :tablefill

    背景(问题) 在Web后台系统中或多或少都存在导入数据的功能,其中操作流程基本是 1.下载模板 2.填充模板数据 3.上传模板 但通常比较耗费时间的是填充模板数据这一步骤, 已自己为例之前的数据要么是 ...

  10. Vulnhub靶机渗透 -- DC6

    信息收集 开启了22ssh和80http端口 ssh可以想到的是爆破,又或者是可以在靶机上找到相应的靶机用户信息进行登录,首先看一下网站信息 结果发现打开ip地址,却显示找不到此网站 但是可以发现地址 ...