本篇内容介绍了“怎么解决shiro会话超时302问题”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
产生异常的情况:nginx配置了https,但是nginx转发请求到web应用走的http,会话超时,shiro会重定向到登录页,这时重定向的是http地址,比如http://xxxxx/login/index ,浏览器会阻止这样的请求(从https页面发起http请求是非法的)。
重写shiro的FormAuthenticationFilter
public class MyShiroAuthcFilter extends FormAuthenticationFilter {
public MyShiroAuthcFilter(String loginUrl) {
super();
setLoginUrl(loginUrl);
}
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
if (isLoginRequest(request, response)) {
return super.onAccessDenied(request, response);
} else {
if (isAjax((HttpServletRequest) request)) { // 处理ajax请求
HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
httpServletResponse.addHeader("REQUIRE_AUTH", "true"); // ajax全局设置中有用
httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); // 改变302状态码
} else {
saveRequest(request);
request.getRequestDispatcher(getLoginUrl()).forward(request, response);
// 由于是nginx转发的,redirect 302会重定向到http协议,不是浏览器期望的https
// saveRequestAndRedirectToLogin(request, response);
}
return false;
}
}
private boolean isAjax(HttpServletRequest request) {
String requestedWithHeader = request.getHeader("X-Requested-With");
return "XMLHttpRequest".equals(requestedWithHeader);
}
}
shiro的filter配置
@Bean
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
String loginUrl = "/login/index";
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
Map<String, Filter> filters = shiroFilter.getFilters();
filters.put("anon", new AnonymousFilter());
filters.put("authc", new MyShiroAuthcFilter(loginUrl));
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/supervisor/**", "authc");
filterChainDefinitionMap.put("/**", "anon");
shiroFilter.setSecurityManager(securityManager);
shiroFilter.setLoginUrl(loginUrl);
shiroFilter.setUnauthorizedUrl("/login/unauthorized");
shiroFilter.setFilters(filters);
shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilter;
}
ajax全局设置
$.ajaxSetup({
complete: function (xhr, status) {
if (xhr.getResponseHeader('REQUIRE_AUTH') == 'true') {
alert("未登录或登录超时!");
window.top.location.href = getHost() + '/login/index';
return;
}
}
});
/login/index页面处理
<script type="text/javascript">
// 使登录页出现在“顶级”窗口,调整浏览器的url地址,上面的filter是forward到登录页的
if(window.top != window.self || location.pathname != '/login/index') {
window.top.location = getHost() + '/login/index';
}
</script>
“怎么解决shiro会话超时302问题”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/2007041/blog/3116895