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. Vue状态管理Vuex简单使用

    状态管理保存在store\index.js中,简单说明如下 import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export def ...

  2. pibbtimq高级使用技术,双向通信

    本案例目是是服务端发送客户端,客户端收到反应给服务端,双向通信客户端代码如下:import pikaimport timeconnection = pika.BlockingConnection(pi ...

  3. 【Python学习】print语句

    一.print 可以向屏幕上输出信息,print 后面一个空格再加上''中间放入要输出的内容. 二.print可以用逗号分隔语句,但是每有一个逗号就会出来一个空格. 1 >>> pr ...

  4. oracle 基础SQL语句 增删改

    一.SQL操作 查询已创建的数据库:SELECT datname FROM pg_database; 创建数据库:CREATE DATABASE wzxdb; 删除数据库:DROP DATABASE ...

  5. 远程连接centos7中mysql8.0

    远程连接centos7中mysql8.0 1.使用Navicat for MySQL或者其它数据连接软件 2.先检查centos中防火墙是否关闭,如果关闭不需要设置,如果没有关闭防火墙,请打开3306 ...

  6. CF235D-Graph Game【LCA,数学期望】

    正题 题目链接:https://www.luogu.com.cn/problem/CF235D 题目大意 给出一棵基环树,每次随机选择一个点让权值加上这个点的连通块大小然后删掉这个点. 求删光所有点时 ...

  7. Python第3方模块安装

    前言: 我们在实际开发过程中,很多模块是Python没有自带的,所以我们使用模块前需要先安装第三方模块. 在线安装: 1.为了简便cmd指令操作,建议先打开Python目录下的Scripts文件夹下, ...

  8. 让前端的下拉框支持单选、多选及全选,后台MyBaits解决方案

    目录 一.解决思路 二.请求参数 三.后台相关代码 四.Mybatis注意要点 一.解决思路   让前端的下拉框支持单选.多选及全选,后台让Mybatis使用** trim **标签拼接动态SQL,实 ...

  9. 踩坑系列《十三》解决时间戳long转换int溢出(即转换值为负数)

    最近业务需求,需要使用到 int 类型的时间戳,所以在使用时间戳的时候,由于java自带的 System.currentTimeMillis() 返回的类型是long,强行转换一波的话,是会出现数据溢 ...

  10. BurpSuite 功能概览

    简介 写作思想:相比较具体介绍某个功能的用法.会更加侧重于介绍 Burp 提供哪些功能.这样好处是在比较复杂的测试场景,如果Burp 刚好提供对应的功能,就不用花费精力造轮子了. 而需要掌握具体操作方 ...