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 ...
随机推荐
- 【异常】 Could not find Linker 'g++' in system path.
1 详细异常 FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':az-ex ...
- asp.net 设计音乐网站
第一步 收集资料 http://www.logoko.com.cn/ --设计logo网站 设计音乐文档 https://wenku.baidu.com/view/3d957617f18583 ...
- 牛客练习赛51 C 勾股定理 (数学,结论)
链接:https://ac.nowcoder.com/acm/contest/1083/C来源:牛客网 题目描述 给出直角三角形其中一条边的长度n,你的任务是构造剩下的两条边,使这三条边能构成一个直角 ...
- Spring管理Hibernate事务
在没有加入Spring来管理Hibernate事务之前,Hibernate对事务的管理的顺序是: 开始事务 提交事务 关闭事务 这样做的原因是Hibernate对事务默认是手动提交,如果不想手动提交, ...
- Android之Json
Servlet部分 public class JasonAction extends HttpServlet { private JsonService service; public void do ...
- 二叉堆的应用——查找长度为N数组中第M大数
看到这个题目首先想到是排序,那么时间复杂度自然就是O(NlgN).那么使用二叉堆如何解决呢? 对于下面一个数组,共有12个元素,我们的目标就是找出第5大元素——12 首先建立一个具有M个元素的最小堆, ...
- cubemx+stm32串口学习汇总资料
这篇文章是串口中断的文章--STM32基于CubeMX的高速串口收发程序(中断模式)比较有帮助. http://www.stmcu.org.cn/module/forum/thread-616613- ...
- 粗暴,干就完了----徐晓冬似的C语言自学笔记-----实现一个链表结构
#include <stdio.h> #include <stdlib.h> #define N 5 /*N 假定数组长度为5*/ typedef struct snode { ...
- Qt 程序自动重启的实现
正常退出调用exit() 或quit()就行,想要自已重启可按下面代码: void XXX:onRestart() { //类中调用 qApp->exit(); } 主main函数中处理 int ...
- Educational Codeforces Round 33 (Rated for Div. 2) B题
B. Beautiful Divisors Recently Luba learned about a special kind of numbers that she calls beautiful ...