公司开发采用Spring Security+AngualerJS框架,在session过期之后,ajax请求会直接出错。本文介绍如何实现出错情况下自动跳转至登录页。

  整体思路是,session过期后,ajax请求返回401 unauthentication错误,前端对$http服务添加拦截器,对401错误进行跳转处理,跳转至登录页。

  由于session过期,需要验证的请求(不论是不是ajax请求)会返回302重定向,我们先配置spring security使之能对ajax请求返回401错误。如下:

  实现自定义的RequestMatcher,当请求是ajax请求即匹配上(angular默认不会带上X-Requested-With,这里通过Accept进行判断,也可以在前端对ajax请求添加X-Requested-With头):

public static class AjaxRequestMatcher implements RequestMatcher {
@Override
public boolean matches(HttpServletRequest request) {
return "XMLHttpRequest".equals(request.getHeader("X-Requested-With")) ||
request.getHeader("Accept") != null &&
request.getHeader("Accept").contains("application/json");
}
}

  实现自定义的AuthenticationEntryPoint,返回401错误:

@Component
public class AjaxAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
} }

  配置错误处理,对ajax请求使用AjaxAuthenticationEntryPoint(

  .exceptionHandling()
        .defaultAuthenticationEntryPointFor(authenticationEntryPoint, new AjaxRequestMatcher())):

    @Autowired
private AuthenticationEntryPoint authenticationEntryPoint; protected void configure(HttpSecurity http) throws Exception {
http
.headers()
.cacheControl()
.and()
.authorizeRequests()
.antMatchers(
"/login",
"/css/**",
"/img/**",
"/js/**",
"/partial/**",
"/script/**",
"/upload/**",
"/plugin/**").permitAll()
.antMatchers("/**")
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.defaultSuccessUrl("/app.html", true)
.and()
.logout()
.logoutUrl("/logout")
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login")
.and()
.exceptionHandling()
.defaultAuthenticationEntryPointFor(authenticationEntryPoint, new AjaxRequestMatcher())
.and()
.csrf().disable();
}

  前端,添加拦截器:

angular.module('app', [])
.config(function($httpProvider) {
$httpProvider.interceptors.push(function($q, $window) {
return {
// optional method
'request': function(config) {
// do something on success
return config;
},
// optional method
'requestError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
},
// optional method
'response': function(response) {
// do something on success
return response;
},
// optional method
'responseError': function(rejection) {
// do something on error
if (rejection.status === 401) {
// return responseOrNewPromise
console.log('401');
$window.location.href = 'login?expired';
}
return $q.reject(rejection);
}
};
});
});

Spring Security登录超时,angular ajax请求出错自动跳转至登录页(jQuery也适用)的更多相关文章

  1. 处理jquery的ajax请求session过期跳转到登录页面

    首先需要在拦截器中判断是否是ajax请求,如果是 if(isAjaxRequest(request)){//ajax请求 response.setHeader("sessionstatus& ...

  2. Spring Security OAuth2 微服务认证中心自定义授权模式扩展以及常见登录认证场景下的应用实战

    一. 前言 [APP 移动端]Spring Security OAuth2 手机短信验证码模式 [微信小程序]Spring Security OAuth2 微信授权模式 [管理系统]Spring Se ...

  3. ajax Session失效如何跳转到登录页面

    在Struts应用中,我们发出的请求都会经过 相应的拦截器进行相关处理,一般都会有一个用户登录拦截(Session失效拦截):一般请求的话,如果Session失效时,我们会跳到登录页面,可是如果我们采 ...

  4. 程序启动的目录不一样.ajax请求的地址跳转会出现的问题

    程序启动的目录不一样.ajax请求的地址跳转会出现的问题启动 frontend/web/启动 frontend/ $.ajax({ url:"<?php echo Yii::$app- ...

  5. 前端跳转处理--房天下的访问页面部分ip自动跳转到登录页面的解决办法(xjl456852原创)

    朋友说自己在访问房天下的页面时,他们页面进行了跳转,跳转到登录页面,说是前端跳转.让我也看看,我看我的机器没有进行跳转. 后来就发现有的机器在访问页面会自动跳转到登录页面.有的不会进行跳转. 比如访问 ...

  6. SpringBoot + Spring Security 学习笔记(一)自定义基本使用及个性化登录配置

    官方文档参考,5.1.2 中文参考文档,4.1 中文参考文档,4.1 官方文档中文翻译与源码解读 SpringSecurity 核心功能: 认证(你是谁) 授权(你能干什么) 攻击防护(防止伪造身份) ...

  7. angular ajax请求 结果显示显示两次的问题

    angular 项目中,由于用到ajax 请求,结果显示如下情况 同样的接口,显示两次,其中第一次请求情况为 request method 显示为opttions 第二次的情况是 为啥会出现如此的情况 ...

  8. Spring Security框架下实现两周内自动登录"记住我"功能

    本文是Spring Security系列中的一篇.在上一篇文章中,我们通过实现UserDetailsService和UserDetails接口,实现了动态的从数据库加载用户.角色.权限相关信息,从而实 ...

  9. Filter实现session超时自动跳转到login页,超过试用期不许登录

    新建一个过滤器 package com.autumn.filter; import com.autumn.pojo.Users; import javax.servlet.*; import java ...

随机推荐

  1. Redis分布式缓存安装和使用

    独立缓存服务器: LinuxCentOS Redis版本: 3.0 下面我们针对于Redis安装做下详细的记录: 编译和安装所需的包: #yum install gcc tcl创建安装目录:贵州中医肝 ...

  2. 常用Linux文件系统

  3. 《浏览器工作原理与实践》<04>从输入URL到页面展示,这中间发生了什么?

    “在浏览器里,从输入 URL 到页面展示,这中间发生了什么? ”这是一道经典的面试题,能比较全面地考察应聘者知识的掌握程度,其中涉及到了网络.操作系统.Web 等一系列的知识. 在面试应聘者时也必问这 ...

  4. python异步编程 (转载)

    Python Async/Await入门指南   转自:https://zhuanlan.zhihu.com/p/27258289 本文将会讲述Python 3.5之后出现的async/await的使 ...

  5. linux入门常用指令4.挂载数据盘

    挂载硬盘 #查看当前分区情况 [root@localhost ~]# lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sdb 8:16 0 5G 0 dis ...

  6. mysql基础_操作文件中的内容

    1.插入数据: insert into t1(id,name) values(1,'alex'); #向t1表中插入id为1,name为'alex'的一条数据 2.删除: delete from t1 ...

  7. Elasticsearch:运用scroll接口对大量数据实现更好的分页

    在Elasticsearch中,我们可以通过size和from来对我们的结果来进行分页.但是对于数据量很大的索引,这是有效的吗?Scroll API可用于从单个搜索请求中检索大量结果(甚至所有结果), ...

  8. 洛谷 P1600 天天爱跑步(LCA+乱搞)

    传送门 我们把每一条路径拆成$u->lca$和$lca->v$的路径 先考虑$u->lca$,如果这条路径会对路径上的某一个点产生贡献,那么满足$dep[u]-dep[x]=w[x] ...

  9. mysql批量新增和批量删除

    首先推荐使用PreparedStatement的批量处理操作. Connection conn = null; PreparedStatement stmt = null; try{ Class.fo ...

  10. [jenkins] 启动错误 Failed to start LSB: Jenkins Automation Server.

    解决办法见https://blog.csdn.net/qq_34208844/article/details/87865672