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

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

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

二、
当session超时后去,ajax请求访问后台,此时会被SessionManagementFilter进行拦截,由下图中可知,此时需要
重写 InvalidSessionStrategy 类。


  1. @Slf4j
  2. public class SimpleAjaxAndRedirectInvalidSessionStrategy implements InvalidSessionStrategy {
  3. private final String destinationUrl;
  4. private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
  5. private boolean createNewSession = true;
  6. public SimpleAjaxAndRedirectInvalidSessionStrategy(String invalidSessionUrl) {
  7. Assert.isTrue(UrlUtils.isValidRedirectUrl(invalidSessionUrl), "url must start with '/' or with 'http(s)'");
  8. this.destinationUrl = invalidSessionUrl;
  9. }
  10. @Override
  11. public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
  12. if (Objects.equals(request.getHeader("X-Requested-With"), "XMLHttpRequest")) {
  13. response.setContentType("text/html;charset=utf-8");
  14. response.setCharacterEncoding("utf-8");
  15. response.getWriter().write("session-timeout");
  16. response.getWriter().close();
  17. } else {
  18. log.debug("Starting new session (if required) and redirecting to '" + destinationUrl + "'");
  19. if (createNewSession) {
  20. request.getSession();
  21. }
  22. redirectStrategy.sendRedirect(request, response, destinationUrl);
  23. }
  24. }
  25. /**
  26. * Determines whether a new session should be created before redirecting (to avoid
  27. * possible looping issues where the same session ID is sent with the redirected
  28. * request). Alternatively, ensure that the configured URL does not pass through the
  29. * {@code SessionManagementFilter}.
  30. *
  31. * @param createNewSession defaults to {@code true}.
  32. */
  33. public void setCreateNewSession(boolean createNewSession) {
  34. this.createNewSession = createNewSession;
  35. }
  36. }

注:一般ajax请求都有一个请求头X-Requeseted-With,且它的值是XMLHttpRequest

       如果涉及到跨域可能没有这个请求头,那么我们可以重写ajax请求加上一个自定义的请求头,只要能判断出ajax请求即可。
三、session是新建的,用户是匿名用户,此时ajax请求是访问一个受限的方法,由下图可知,此时需要重写
AuthenticationEntryPoint


  1. public class HandleAnonyAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
  2. /**
  3. * @param loginFormUrl URL where the login page can be found. Should either be
  4. * relative to the web-app context path (include a leading {@code /}) or an absolute
  5. * URL.
  6. */
  7. public HandleAnonyAuthenticationEntryPoint(String loginFormUrl) {
  8. super(loginFormUrl);
  9. }
  10. @Override
  11. public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
  12. if (Objects.equals(request.getHeader("X-Requested-With"), "XMLHttpRequest")) {
  13. response.setContentType("text/html;charset=utf-8");
  14. response.setCharacterEncoding("utf-8");
  15. response.getWriter().write("session-timeout");
  16. response.getWriter().close();
  17. } else {
  18. super.commence(request, response, authException);
  19. }
  20. }
  21. }

  四、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. 细谈布隆过滤器及Redis实现

    ​ 何为布隆过滤器? 本质上是一种数据结构,是1970年由布隆提出的.它实际上是一个很长的二进制向量(位图)和一系列随机映射函数(哈希函数).可以用于检索一个元素是否在一个集合中. 数据结构: 布隆过 ...

  2. SpringSecurity-Shiro-初见

    目录 简介 实战环境搭建 SpringSecurity 认证和授权 权限控制和注销 记住我 Shiro 快速上手 shiro整合mybais 简介 在 Web 开发中,安全一直是非常重要的一个方面. ...

  3. 分享一则Linux系统邮件提示 /usr/local/lib/libprocesshider.so > /etc/ld.so.preload 的中病毒解决方法

    ​ 系统环境:CentOS Linux release 7.6.1810 (AltArch)                   CPU架构:ARM            最近发现生产服务器CPU占用 ...

  4. sass和js的联动(共享变量)

    一般做共享变量用于主题功能 假设我们在xxx.scss中声明了一个 theme:blue,我们在 js 中该怎么获取这个变量呢?我们可以通过import variables from '@/style ...

  5. Spring Boot 2.x 之 H2 数据库

    1. Spring Boot下H2数据库的常用配置项 # 指定数据库的类型 spring.datasource.platform=h2 # 数据库连接地址(文件模式) ## AUTO_SERVER=T ...

  6. python中reduce filter map lambda函数

    lambda函数 python 使用 lambda 来创建匿名函数,lambda返回值是一个函数的地址,也就是函数对象. 语法:lambda [arg1 [,arg2,.....argn]]:expr ...

  7. 洛谷P1019——单词接龙(DFS暴力搜索)

    https://www.luogu.org/problem/show?pid=1019#sub 题目描述 单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定一个开头的字母, ...

  8. POJ1741——Tree(树的点分治)

    1 /* *********************************************** 2 Author :kuangbin 3 Created Time :2013-11-17 1 ...

  9. VBox 虚拟机安装 Openwrt 做旁路由

    VBox 虚拟机安装 Openwrt 做旁路由 需求:开个虚拟机做旁路由,电脑把网关设置成旁路由地址,用它跑个上网或其他什么东西. 安装及配置过程简述 这件事流程很简单,总结起来主要有以下几点: 安装 ...

  10. php去除html标签

    function cutstr_html($string){ $string = strip_tags($string); $string = preg_replace(["\t" ...