1. 程式人生 > >shiro用authc配置後登入成功後不能跳轉到index頁面

shiro用authc配置後登入成功後不能跳轉到index頁面

這兩天發現一個問題,如題,嘗試了很多方法,都沒法解決,真是很鬱悶。最後看原始碼才知道,我的配置如下。原意是從/api/user/login登入成功後,跳轉到/index,但是怎麼都不能跳轉到/index。原來authc攔截器(即FormAuthenticationFilter),驗證成功後只會跳轉到最開始你進入的頁面,因為我是從/api/user/login頁面進入登入,所以只會跳轉到/api/user/login。要想跳轉到/index頁面,只有最開始從/index頁面進入,後臺會重定向到/api/user/login頁面,驗證成功後,才返回/index頁面。

配置如下:

    <!-- Shiro的Web過濾器 ,id要與web.xml一致 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <property name="loginUrl" value="/api/user/login" /> <property name="successUrl" value="/index" /> <property
name="unauthorizedUrl" value="/unauthorized" />
<property name="filters"> <map> <entry key="authc" value-ref="formAuthenticationFilter" /> </map> </property> <property name="filterChainDefinitions"> <value
>
/static/** = anon /api/user/login = authc /api/user/logout = logout /api/user/register* = anon /unauthorized = anon /** = user </value> </property> </bean>

FormAuthenticationFilter部分原始碼:

    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
                                     ServletRequest request, ServletResponse response) throws Exception {
        issueSuccessRedirect(request, response);
        //we handled the success redirect directly, prevent the chain from continuing:
        return false;
    }

從原始碼我們可以看出,登入成功後,會執行

     protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
        WebUtils.redirectToSavedRequest(request, response, getSuccessUrl());
    }

這個方法就是

   public static void redirectToSavedRequest(ServletRequest request, ServletResponse response, String fallbackUrl)
            throws IOException {
        String successUrl = null;
        boolean contextRelative = true;
        SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(request);
        if (savedRequest != null && savedRequest.getMethod().equalsIgnoreCase(AccessControlFilter.GET_METHOD)) {
            successUrl = savedRequest.getRequestUrl();
            contextRelative = false;
        }

        if (successUrl == null) {
            successUrl = fallbackUrl;
        }

        if (successUrl == null) {
            throw new IllegalStateException("Success URL not available via saved request or via the " +
                    "successUrlFallback method parameter. One of these must be non-null for " +
                    "issueSuccessRedirect() to work.");
        }

        WebUtils.issueRedirect(request, response, successUrl, null, contextRelative);
    }

關鍵在於successUrl = savedRequest.getRequestUrl(),會把successUrl重新賦值,配置的/index失效。