Shiro Ajax 302 跳轉(zhuǎn)問(wèn)題

版本:

  • Spring Boot 1.5.4.RELEASE
  • Shiro 1.4.0

問(wèn)題

當(dāng)session超時(shí)后,發(fā)起Ajax請(qǐng)求(查詢更新表格內(nèi)容),頁(yè)面沒(méi)有跳轉(zhuǎn)到登陸畫(huà)面。

原因

因?yàn)槭褂昧薙hiro,默認(rèn)的“authc”是FormAuthenticationFilter 過(guò)濾器,該類中的onAccessDenied方法如下,從中可以看出:當(dāng)訪問(wèn)被拒,并且不是登錄請(qǐng)求時(shí),會(huì)重定向(302)到登錄URL。

protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    if (isLoginRequest(request, response)) {
        if (isLoginSubmission(request, response)) {
            if (log.isTraceEnabled()) {
                log.trace("Login submission detected.  Attempting to execute login.");
            }
            return executeLogin(request, response);
        } else {
            if (log.isTraceEnabled()) {
                log.trace("Login page view.");
            }
            //allow them to see the login page ;)
            return true;
        }
    } else {
        if (log.isTraceEnabled()) {
            log.trace("Attempting to access a path which requires authentication.  Forwarding to the " +
                      "Authentication url [" + getLoginUrl() + "]");
        }
        // 這里重定向到登錄畫(huà)面
        saveRequestAndRedirectToLogin(request, response);
        return false;
    }
}

如果不是Ajax請(qǐng)求,是沒(méi)有問(wèn)題的,瀏覽器可以正常跳轉(zhuǎn)到登陸畫(huà)面。如果是jQuery Ajax請(qǐng)示,則ajaxComplete事件最終拿到的response status是redirect之后的status,即訪問(wèn)登陸畫(huà)面后的響應(yīng)狀態(tài)200。

解決方法

重寫(xiě)FormAuthenticationFilter 類的onAccessDenied方法,并判斷如果請(qǐng)求是ajax請(qǐng)求,就在header中添加一個(gè)需要登錄的標(biāo)識(shí),并且設(shè)置response status為401,避免還是200而繼續(xù)走ajax的成功回調(diào)。然后Ajax添加全局事件,當(dāng)有需要登錄的標(biāo)識(shí)時(shí),將頁(yè)面定位到登錄畫(huà)面。

重寫(xiě)FormAuthenticationFilter

public class MyShiroAuthcFilter extends FormAuthenticationFilter {

    public MyShiroAuthcFilter() {
        super();
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            return super.onAccessDenied(request, response);
        } else {
            if (isAjax((HttpServletRequest) request)) {
                HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
                httpServletResponse.addHeader("REQUIRE_AUTH", "true");
                httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
            } else {
                saveRequestAndRedirectToLogin(request, response);
            }
            return false;
        }
    }

    private boolean isAjax(HttpServletRequest request) {
        String requestedWithHeader = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equals(requestedWithHeader);
    }
}

配置重寫(xiě)后的filter

@Configuration
public class ShiroConfig {

    @Bean
    public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver) {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver);
        final ShiroDialect dialect = new ShiroDialect();
        engine.addDialect(dialect);
        return engine;
    }

//    @Bean
//    public HashedCredentialsMatcher hashedCredentialsMatcher(){
//        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
//        credentialsMatcher.setHashAlgorithmName("SHA1");
//        credentialsMatcher.setHashIterations(5);
//        credentialsMatcher.setStoredCredentialsHexEncoded(true);
//        return credentialsMatcher;
//    }

    @Bean
    public MyShiroRealm myShiroRealm() {
        MyShiroRealm myShiroRealm = new MyShiroRealm();
//        myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return myShiroRealm;
    }

    @Bean
    public EhCacheManager ehCacheManager() {
        EhCacheManager cacheManager = new EhCacheManager();
        return cacheManager;
    }

    @Bean
    public SecurityManager securityManager(MyShiroRealm myShiroRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(myShiroRealm);
        securityManager.setCacheManager(ehCacheManager());
        securityManager.getSessionManager();
        return securityManager;
    }

//    @Bean
//    public MyShiroAuthcFilter myShiroAuthcFilter() {
//        MyShiroAuthcFilter myShiroAuthcFilter = new MyShiroAuthcFilter();
//        return myShiroAuthcFilter;
//    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    @Bean
    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean filter = new ShiroFilterFactoryBean();
        filter.setSecurityManager(securityManager);
        filter.setLoginUrl("/login");
        filter.setSuccessUrl("/index");
        filter.setUnauthorizedUrl("/403");
        filter.setUnauthorizedUrl("/404");
        filter.setUnauthorizedUrl("/500");

        Map<String, Filter> filters = filter.getFilters();
//        filters.put("authd", myShiroAuthcFilter());
        // 注意這里不要用Bean的方式,否則會(huì)報(bào)錯(cuò)
        filters.put("authd", new MyShiroAuthcFilter());
        filters.put("anon", new AnonymousFilter());
        filters.put("logout", new LogoutFilter());
        filter.setFilters(filters);

        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/resources/**", "anon");
        filterChainDefinitionMap.put("/loginSubmit", "anon");
        filterChainDefinitionMap.put("/logout", "logout");
        filterChainDefinitionMap.put("/**", "authd");
        filter.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return filter;
    }

    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }
}

Ajax全局事件

$(document).ready(function() {
    // 解決session超時(shí),Ajax請(qǐng)求頁(yè)面不跳轉(zhuǎn)的問(wèn)題
    $(document).ajaxComplete(function(event, xhr, settings) {
        if (xhr.getResponseHeader('REQUIRE_AUTH') === 'true') {
            window.location.href = ctx + "/index";
        }
    });
});

參考:

https://stackoverflow.com/questions/30461823/spring-mvc-detect-ajax-request

https://stackoverflow.com/questions/199099/how-to-manage-a-redirect-request-after-a-jquery-ajax-call

http://shiro-user.582556.n2.nabble.com/redirect-302-Found-td5769710.html

https://blog.csdn.net/callmesong/article/details/78826696

http://shiro-user.582556.n2.nabble.com/Session-Timeout-doesn-t-redirect-to-login-page-td7577730.html

http://shiro-user.582556.n2.nabble.com/Web-Filter-to-return-HTTP-status-code-td7577672.html

https://shiro.apache.org/spring-framework.html

https://shiro.apache.org/spring-boot.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,688評(píng)論 19 139
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong閱讀 22,966評(píng)論 1 92
  • 浮世志 濁濁浮華世 浮塵惹青衣 心有凌云志 卻為浮世累 憐花 陌上花開(kāi)出浮塵 花出浮塵未染塵 未染塵花惹世人 惹來(lái)...
    浮塵自憐閱讀 431評(píng)論 0 0
  • dacheng閱讀 360評(píng)論 0 1
  • 原來(lái) 在那個(gè)春意萌動(dòng)的年紀(jì) 太急于品嘗戀愛(ài)的滋味 以至于忘記挑選自己真正喜歡的 所以才會(huì)留有遺憾 愿你的愛(ài)情 遇到對(duì)的人
    婉言1228閱讀 362評(píng)論 0 0

友情鏈接更多精彩內(nèi)容