您好,登錄后才能下訂單哦!
本篇內容介紹了“怎么解決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問題”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。