Spring Security登录超时,angular ajax请求出错自动跳转至登录页(jQuery也适用)
公司开发采用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也适用)的更多相关文章
- 处理jquery的ajax请求session过期跳转到登录页面
首先需要在拦截器中判断是否是ajax请求,如果是 if(isAjaxRequest(request)){//ajax请求 response.setHeader("sessionstatus& ...
- Spring Security OAuth2 微服务认证中心自定义授权模式扩展以及常见登录认证场景下的应用实战
一. 前言 [APP 移动端]Spring Security OAuth2 手机短信验证码模式 [微信小程序]Spring Security OAuth2 微信授权模式 [管理系统]Spring Se ...
- ajax Session失效如何跳转到登录页面
在Struts应用中,我们发出的请求都会经过 相应的拦截器进行相关处理,一般都会有一个用户登录拦截(Session失效拦截):一般请求的话,如果Session失效时,我们会跳到登录页面,可是如果我们采 ...
- 程序启动的目录不一样.ajax请求的地址跳转会出现的问题
程序启动的目录不一样.ajax请求的地址跳转会出现的问题启动 frontend/web/启动 frontend/ $.ajax({ url:"<?php echo Yii::$app- ...
- 前端跳转处理--房天下的访问页面部分ip自动跳转到登录页面的解决办法(xjl456852原创)
朋友说自己在访问房天下的页面时,他们页面进行了跳转,跳转到登录页面,说是前端跳转.让我也看看,我看我的机器没有进行跳转. 后来就发现有的机器在访问页面会自动跳转到登录页面.有的不会进行跳转. 比如访问 ...
- SpringBoot + Spring Security 学习笔记(一)自定义基本使用及个性化登录配置
官方文档参考,5.1.2 中文参考文档,4.1 中文参考文档,4.1 官方文档中文翻译与源码解读 SpringSecurity 核心功能: 认证(你是谁) 授权(你能干什么) 攻击防护(防止伪造身份) ...
- angular ajax请求 结果显示显示两次的问题
angular 项目中,由于用到ajax 请求,结果显示如下情况 同样的接口,显示两次,其中第一次请求情况为 request method 显示为opttions 第二次的情况是 为啥会出现如此的情况 ...
- Spring Security框架下实现两周内自动登录"记住我"功能
本文是Spring Security系列中的一篇.在上一篇文章中,我们通过实现UserDetailsService和UserDetails接口,实现了动态的从数据库加载用户.角色.权限相关信息,从而实 ...
- Filter实现session超时自动跳转到login页,超过试用期不许登录
新建一个过滤器 package com.autumn.filter; import com.autumn.pojo.Users; import javax.servlet.*; import java ...
随机推荐
- linux在配置菜单中添加选项
- Mysql(七):视图、触发器、事务、存储过程、函数
一 视图 视图是一个虚拟表(非真实存在),其本质是[根据SQL语句获取动态的数据集,并为其命名],用户使用时只需使用[名称]即可获取结果集,可以将该结果集当做表来使用. 使用视图我们可以把查询过程中的 ...
- 【2017-06-16】Jquery获取dropdownlist选中的内容
var Text = $("#DropDownList1 option:selected").text(); 注意:DropDownList1和option之间有个空格!!!
- java 项目坑记录
1. spring项目引入了lombok jar包,且已在类上面添加@Data注释,还是关联不到 get() 和 set() 方法 需要安装扩展包 如果在线安装失败,提示错误readtime out, ...
- 修改input file 文件上传的样式
Web页面中,在需要上传文件时基本都会用到<input type="file">元素,它的默认样式: chrome下: IE下: 不管是上面哪种,样式都比较简单,和很多 ...
- js修改元素的属性
<script type="text/javascript"> //给id为nice的元素 添加title属性并赋值为"测试title" funct ...
- Java&Selenium&TestNG&ZTestReport 自动化测试并生成HTML自动化测试报告
一.摘要 本篇博文将介绍如何借助ZTestReport和HTML模版,生成HTML测试报告的ZTestReport 源码Clone地址为 https://github.com/zhangfei1984 ...
- 使用原生js 实现点击消失效果
JQ版 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title ...
- MyBatis注解Annotation介绍及Demo(转)
MyBatis可以利用SQL映射文件来配置,也可以利用Annotation来设置.MyBatis提供的一些基本注解如下表所示. 注解 目标 相应的XML 描述 @CacheNamespace 类 &l ...
- curl查看http请求消息的时长
1. -X 指定请求方式GET请求curl -X GET http://www.jackyops.com/search?data=123 # -X GET是可选的 POST请求curl -X POS ...