起因:

项目对接cas认证中心,当服务关闭或者重启,会使客户端session失效,再次请求接口则会出现302问题,后台会进行去登录的跳转,状态err_failed。

思路:

我们能不能在进行cas处理前判断当前session是否有效,通过filter

解决:

1、自定义拦截器,并添加到cas过滤器中;
2、对过期的session,通过响应一个状态码让前端处理,跳转到登录页,这里处理是刷新reload下;

1、cas拦截配置 –new CasAuthenticationFilter()

@Component
@EnableCasClient
@Order(0)
public class CasConfig extends CasClientConfigurerAdapter {@Resourceprivate GlobalParamConfig globalParamConfig;@Overridepublic void configureAuthenticationFilter(FilterRegistrationBean authenticationFilter) {super.configureAuthenticationFilter(authenticationFilter);//配置自定义过滤器authenticationFilter.setFilter(new CasAuthenticationFilter());authenticationFilter.addUrlPatterns("/*");authenticationFilter.getInitParameters().put("ignorePattern", globalParamConfig.ignorePattern);//自定义UrlPatternMatcherStrategy 过滤规则authenticationFilter.addInitParameter("ignoreUrlPatternType", ignoreUrlPatternType);authenticationFilter.setOrder(0);

2、自定义过滤器

@Component
public class CasAuthenticationFilter extends AbstractCasFilter {private String casServerLoginUrl;private boolean renew;private boolean gateway;private GatewayResolver gatewayStorage;private AuthenticationRedirectStrategy authenticationRedirectStrategy;private UrlPatternMatcherStrategy ignoreUrlPatternMatcherStrategyClass;private static final Map<String, Class<? extends UrlPatternMatcherStrategy>> PATTERN_MATCHER_TYPES = new HashMap();/*** 构造方法*/public MyAuthenticationFilter() {this(Protocol.CAS2);}protected MyAuthenticationFilter(Protocol protocol) {super(protocol);this.renew = false;this.gateway = false;this.gatewayStorage = new DefaultGatewayResolverImpl();this.authenticationRedirectStrategy = new DefaultAuthenticationRedirectStrategy();this.ignoreUrlPatternMatcherStrategyClass = null;}protected void initInternal(FilterConfig filterConfig) throws ServletException {if (!this.isIgnoreInitConfiguration()) {super.initInternal(filterConfig);this.setCasServerLoginUrl(this.getString(ConfigurationKeys.CAS_SERVER_LOGIN_URL));this.setRenew(this.getBoolean(ConfigurationKeys.RENEW));this.setGateway(this.getBoolean(ConfigurationKeys.GATEWAY));String ignorePattern = this.getString(ConfigurationKeys.IGNORE_PATTERN);String ignoreUrlPatternType = this.getString(ConfigurationKeys.IGNORE_URL_PATTERN_TYPE);Class gatewayStorageClass;if (ignorePattern != null) {gatewayStorageClass = (Class) PATTERN_MATCHER_TYPES.get(ignoreUrlPatternType);if (gatewayStorageClass != null) {this.ignoreUrlPatternMatcherStrategyClass = (UrlPatternMatcherStrategy) ReflectUtils.newInstance(gatewayStorageClass.getName(), new Object[0]);} else {try {this.logger.trace("Assuming {} is a qualified class name...", ignoreUrlPatternType);this.ignoreUrlPatternMatcherStrategyClass = (UrlPatternMatcherStrategy) ReflectUtils.newInstance(ignoreUrlPatternType, new Object[0]);} catch (IllegalArgumentException var6) {this.logger.error("Could not instantiate class [{}]", ignoreUrlPatternType, var6);}}if (this.ignoreUrlPatternMatcherStrategyClass != null) {this.ignoreUrlPatternMatcherStrategyClass.setPattern(ignorePattern);}}gatewayStorageClass = this.getClass(ConfigurationKeys.GATEWAY_STORAGE_CLASS);if (gatewayStorageClass != null) {this.setGatewayStorage((GatewayResolver) ReflectUtils.newInstance(gatewayStorageClass, new Object[0]));}Class<? extends AuthenticationRedirectStrategy> authenticationRedirectStrategyClass = this.getClass(ConfigurationKeys.AUTHENTICATION_REDIRECT_STRATEGY_CLASS);if (authenticationRedirectStrategyClass != null) {this.authenticationRedirectStrategy = (AuthenticationRedirectStrategy) ReflectUtils.newInstance(authenticationRedirectStrategyClass, new Object[0]);}}}/*** 初始化*/public void init() {super.init();CommonUtils.assertNotNull(this.casServerLoginUrl, "casServerLoginUrl cannot be null.");}/*** 核心方法** @param servletRequest* @param servletResponse* @param filterChain* @throws IOException* @throws ServletException*/public final void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) servletRequest;HttpServletResponse response = (HttpServletResponse) servletResponse;//判断是否是不必要拦截的请求地址if (this.isRequestUrlExcluded(request)) {this.logger.debug("Request is ignored.");filterChain.doFilter(request, response);} else {//获取session,判断session是否失效HttpSession session = request.getSession(false);Assertion assertion = session != null ? (Assertion) session.getAttribute("_const_cas_assertion_") : null;if (assertion != null) {filterChain.doFilter(request, response);} else {//session失效判断票据和断言String serviceUrl = this.constructServiceUrl(request, response);String ticket = this.retrieveTicketFromRequest(request);boolean wasGatewayed = this.gateway && this.gatewayStorage.hasGatewayedAlready(request, serviceUrl);if (!CommonUtils.isNotBlank(ticket) && !wasGatewayed) {this.logger.debug("no ticket and no assertion found");String modifiedServiceUrl;if (this.gateway) {this.logger.debug("setting gateway attribute in session");modifiedServiceUrl = this.gatewayStorage.storeGatewayInformation(request, serviceUrl);} else {modifiedServiceUrl = serviceUrl;}//获取请求路径this.logger.debug("Constructed service url: {}", modifiedServiceUrl);String urlToRedirectTo = CommonUtils.constructRedirectUrl(this.casServerLoginUrl, this.getProtocol().getServiceParameterName(), modifiedServiceUrl, this.renew, this.gateway);//判断请求方式是否为ajax请求String header = request.getHeader("X-Requested-With");
//                    String header1 = request.getHeader("x-version-type");if ("XMLHttpRequest".equals(header)) { // || (null != header1 && header1.equals("Admin"))//给这个请求打上标记(登录已经超时或者认证未通过)ajaxHttpToLogin(request, response, loginUrl);} else {this.logger.debug("redirecting to \"{}\"", urlToRedirectTo);this.authenticationRedirectStrategy.redirect(request, response, urlToRedirectTo);}/* String urls = urlToRedirectTo;response.setContentType("text/html;charset=UTF-8");response.getWriter().write("<script language='javascript'>window.location.href='" + urls + "/'</script>");*/} else {filterChain.doFilter(request, response);}}}}/*** ajax请求标记** @param request* @param response* @param loginUrl*/private void ajaxHttpToLogin(HttpServletRequest request, HttpServletResponse response, String loginUrl) {try {//这里响应状态码为自定义,前端根据状态去处理response.setStatus(ResultCodeEnum.SESSION_EXPIRED.getCode());//403 禁止response.getWriter().print(JSONObject.toJSONString(new ResultVo<>(ResultCodeEnum.SESSION_EXPIRED, new Message("error", ResultCodeEnum.SESSION_EXPIRED.getMsg()))));} catch (Exception e) {e.printStackTrace();}}public final void setRenew(boolean renew) {this.renew = renew;}public final void setGateway(boolean gateway) {this.gateway = gateway;}public final void setCasServerLoginUrl(String casServerLoginUrl) {this.casServerLoginUrl = casServerLoginUrl;}public final void setGatewayStorage(GatewayResolver gatewayStorage) {this.gatewayStorage = gatewayStorage;}private boolean isRequestUrlExcluded(HttpServletRequest request) {if (this.ignoreUrlPatternMatcherStrategyClass == null) {return false;} else {StringBuffer urlBuffer = request.getRequestURL();if (request.getQueryString() != null) {urlBuffer.append("?").append(request.getQueryString());}String requestUri = urlBuffer.toString();return this.ignoreUrlPatternMatcherStrategyClass.matches(requestUri);}}static {PATTERN_MATCHER_TYPES.put("CONTAINS", ContainsPatternUrlPatternMatcherStrategy.class);PATTERN_MATCHER_TYPES.put("REGEX", RegexUrlPatternMatcherStrategy.class);PATTERN_MATCHER_TYPES.put("EXACT", ExactUrlPatternMatcherStrategy.class);}
}

3、当然第一步也可以FilterRegistrationBean 设置,不一定按照上面来,如下

    @Beanpublic FilterRegistrationBean filterAuthenticationRegistration(){FilterRegistrationBean registrationBean = new FilterRegistrationBean();registrationBean.setFilter(new CasAuthenticationFilter());registrationBean.addUrlPatterns("/*");registrationBean.setOrder(0);return registrationBean;}

就到这吧,ending!

感谢以下博文:

https://blog.csdn.net/chen_bo526/article/details/103924649

Springboot+CAS下Session过期无效,页面请求302问题解决相关推荐

  1. springboot shiro设置session过期时间

    登陆成功之后设置session时间即可 /*** 自定义登录filter*/ public class AuthenticationFilter extends FormAuthenticationF ...

  2. session会话拦截ajax,session过期,拦截ajax请求并跳转登录页面

    1.方法一 :1.1使用filter 和ajaxsetup 对ajax进行拦截并跳转登录页面 public void doFilter(ServletRequest request, ServletR ...

  3. php中session时间,php中session过期时间的设置方法

    php中session过期时间的设置方法 发布时间:2020-04-22 10:21:19 来源:亿速云 阅读:140 作者:小新 今天小编给大家分享的是php中session过期时间的设置方法,相信 ...

  4. CAS的Session两秒挂掉?--解决退出后登录,页面刷新的问题

    版本:Server 3.5.2 ------------------------------------ 现象: 登录成功后,马上点退出. 退出登录后,自动跳转到login页面, 慢一点,等个几秒钟, ...

  5. php ajax session失效,PHP中解决ajax请求session过期退出登录问题

    1.session过期,如果直接是url请求,或者用户在打开的系统页面中直接清除缓存及cookie信息,可直接在php的入口文件中调用以下封装的方法,进行session信息判断以及页面的跳转,如: i ...

  6. ajaxsetup无效_Ajax请求session失效该如何解决

    一般来说我们的项目都有登录过滤器,一般请求足以搞定.但是AJAX却是例外的,所以解决方法是设置响应为session失效. 一共分为过滤器和页面JS两个部分的设置,先看过滤器的修改: import ja ...

  7. session过期跳转登录页面

    2019独角兽企业重金招聘Python工程师标准>>> 项目需要做一个自动登出的功能,查询了网上的资料,一开始准备用session监听做,按照下面方式配置监听器 1.在项目的web. ...

  8. Shiro session过期跳转到登录页面问题

    Shiro session过期跳转到登录页面问题 shrio的session过期后(工程重启或者用户长时间没进行任何操作),当客户端再次向服务端发起请求时,shrio会判断用户没有登录授权,然后对请求 ...

  9. Shiro中Session过期页面跳转回登录页面处理问题

    Session超时的两种情况: shiro在管理session后,在session超时会进行跳转,这里有两种情况需要考虑,一种是ajax方式的请求超时,一种页面跳转请求的超时: 解决问题的思路:通过定 ...

  10. ajaxsetup获取ajax的url_ajaxsetup,组合拦截器处理session过期,跳转登录页面

    当前位置:我的异常网» Ajax » ajaxsetup,组合拦截器处理session过期,跳转登录页面 ajaxsetup,组合拦截器处理session过期,跳转登录页面 www.myexcepti ...

最新文章

  1. java 桶排序_[图解] 桶排序
  2. labview波形图两个游标,LabVIEW数据可视化:使用波形图表控件逐点显示曲线的方法...
  3. django 的用户验证及登录状态保持
  4. ORACLE MTTR
  5. vmlite linux版本,vmlite 安装 xp mode及xp、win7、linux的虚拟磁盘到d盘的方法
  6. c程序预处理器的设计与实现_C预处理器-能力问题与解答
  7. Kubernetes 部署 Ingress 控制器 Traefik v2.1
  8. 从零开始学Pytorch(十一)之ModernRNN
  9. 电子信息工程这个专业学的是什么内容,就业怎么样?
  10. 在SQL数据库中搜索对象的不同方法
  11. vb 饼状图显示百分比_Matplotlib-饼图
  12. 全球闪存供应紧张 新iPhone涨价只是开始
  13. 表情库 android,Emojicon
  14. unity用代码生成的物体或line renderer让其在确定的某一个层里面的方法
  15. hero登录器服务器列表为空,Hero引擎登陆器配置图文教程
  16. 数学建模可以用python_数学建模可以用Python吗
  17. 10月SCI/SSCI/EI刊源更新,新增1区TOP,2022年仅剩不到三个月,还在观望吗?
  18. 《正在爆发的互联网革命》作者个人出资10000美金,面向全球征召六度分割理论实验对象!...
  19. pandas入门与数据准备与简单筛选统计
  20. oracle latch chain,Oracle Latch及latch矛盾

热门文章

  1. 机器学习其实只是“皇帝的新衣”
  2. C4D快速入门教程——可编辑模式
  3. 【Vue: 使用pdf.js顯示PDF Viewer】
  4. 目前为止最全的微信小程序项目实例
  5. Java二进制的符号位在哪一位_Java位运算符及二进制常识
  6. 一般凸二次规划的有效集算法 Matlab程序
  7. Windows10永久关闭自动更新,禁止windows10自动更新方法!
  8. 夜间灯光数据dn值_探讨DMSPOLS夜间灯光数据的校正
  9. JAVA项目开发团队分配
  10. 【Java】快速排序,归并排序,堆排序