《shiro源碼分析【整合spring】》(二)——Shiro過濾器

二、Shiro過濾器

由于我們的分析只是基于web項目的,由配置文件我們可以知道,在web項目中,shiro的入口是一個Filter類。至于filter的初始化,在第一部分已經介紹,接下來我們直接來看該過濾器是如何工作的。
由于集成spring的,這個filter的具體實現類是:org.apache.shiro.spring.web.ShiroFilterFactoryBean.SpringShiroFilter。這是一個內部類。這個類繼承自:org.apache.shiro.web.servlet.AbstractShiroFilter,整個過濾器的核心處理方法都是在這個類實現的,而SpringShiroFilter只是做了一些初始化的工作,具體可以看源碼:


private static final class SpringShiroFilter extends AbstractShiroFilter {
    //構造
    protected SpringShiroFilter(WebSecurityManager webSecurityManager, FilterChainResolver resolver) {
        super();
        if (webSecurityManager == null) {
            throw new IllegalArgumentException("WebSecurityManager property cannot be null.");
        }
        //設置SecurityManager
        setSecurityManager(webSecurityManager);
        //設置FilterChainResolver
        if (resolver != null) {
            setFilterChainResolver(resolver);
        }
    }
}

我們都知道一個過濾器的核心就是doFilter方法,SpringShiroFilter這個類的doFilter方法的實現是由其父類:org.apache.shiro.web.servlet.OncePerRequestFilter實現的。下面來看看這個doFilter方法的具體實現。


public final void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
    String alreadyFilteredAttributeName = getAlreadyFilteredAttributeName();
    //判斷當前過濾器是否已經執行,如果已經執行則不進行任何操作
    if ( request.getAttribute(alreadyFilteredAttributeName) != null ) {
        //日志
        log.trace("Filter '{}' already executed.  Proceeding without invoking this filter.", getName());
        filterChain.doFilter(request, response);
    } else //noinspection deprecation
        if (/* added in 1.2: */ !isEnabled(request, response) ||
            /* retain backwards compatibility: */ shouldNotFilter(request) ) {
        log.debug("Filter '{}' is not enabled for the current request.  Proceeding without invoking this filter.",
                getName());
        filterChain.doFilter(request, response);
    } else {
        // 在這里啟動過濾器
        log.trace("Filter '{}' not yet executed.  Executing now.", getName());
        // 注意:這里將當前的過濾器名字進行存儲
        request.setAttribute(alreadyFilteredAttributeName, Boolean.TRUE);

        try {
            doFilterInternal(request, response, filterChain);
        } finally {
            // Once the request has finished, we're done and we don't
            // need to mark as 'already filtered' any more.
            request.removeAttribute(alreadyFilteredAttributeName);
        }
    }
}

由上面可以看到真正對請求進行過處理的方法時doFilterInternal這個方法。我們直接貼源碼。


protected void doFilterInternal(ServletRequest servletRequest, ServletResponse servletResponse, final FilterChain chain)
        throws ServletException, IOException {

    Throwable t = null;

    try {
        final ServletRequest request = prepareServletRequest(servletRequest, servletResponse, chain);
        final ServletResponse response = prepareServletResponse(request, servletResponse, chain);
        //這里其實就是初始化一個全局的subject對象??梢栽谌魏蔚胤竭M行獲取。
        final Subject subject = createSubject(request, response);
        
        //這一步是主要的處理,有興趣的可以繼續跟蹤下代碼,這里其實就是執行回調里面的方法。
        subject.execute(new Callable() {
            public Object call() throws Exception {
                //看名字就知道這里不重要啦,哈哈!
                updateSessionLastAccessTime(request, response);
                //這個是關鍵
                executeChain(request, response, chain);
                return null;
            }
        });
    } catch (ExecutionException ex) {
        t = ex.getCause();
    } catch (Throwable throwable) {
        t = throwable;
    }

    if (t != null) {
        if (t instanceof ServletException) {
            throw (ServletException) t;
        }
        if (t instanceof IOException) {
            throw (IOException) t;
        }
        //otherwise it's not one of the two exceptions expected by the filter method signature - wrap it in one:
        String msg = "Filtered request failed.";
        throw new ServletException(msg, t);
    }
}

上面的代碼中,關鍵的就是的一個方法是executeChain


protected void executeChain(ServletRequest request, ServletResponse response, FilterChain origChain)
        throws IOException, ServletException {
    FilterChain chain = getExecutionChain(request, response, origChain);
    chain.doFilter(request, response);
}

protected FilterChain getExecutionChain(ServletRequest request, ServletResponse response, FilterChain origChain) {
    FilterChain chain = origChain;
    
    //獲取解析器,如果為空就返回原始的過濾器
    FilterChainResolver resolver = getFilterChainResolver();
    if (resolver == null) {
        log.debug("No FilterChainResolver configured.  Returning original FilterChain.");
        return origChain;
    }
    //從解析器中獲取過濾器。
    FilterChain resolved = resolver.getChain(request, response, origChain);
    if (resolved != null) {
        log.trace("Resolved a configured FilterChain for the current request.");
        chain = resolved;
    } else {
        log.trace("No FilterChain configured for the current request.  Using the default.");
    }

    return chain;
}

//該方法在類:org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver#getChain 中
public FilterChain getChain(ServletRequest request, ServletResponse response, FilterChain originalChain) {
    //獲取過濾器鏈的管理器
    FilterChainManager filterChainManager = getFilterChainManager();
    if (!filterChainManager.hasChains()) {
        return null;
    }
    
    //獲取當前請求的相對路徑
    String requestURI = getPathWithinApplication(request);

    //the 'chain names' in this implementation are actually path patterns defined by the user.  We just use them
    //as the chain name for the FilterChainManager's requirements
    //這個循環就是一個匹配的過程將當前路徑與配置的路徑進行比較,根據配置轉發到想應的過濾器。
    for (String pathPattern : filterChainManager.getChainNames()) {

        // If the path does match, then pass on to the subclass implementation for specific checks:
        if (pathMatches(pathPattern, requestURI)) {
            if (log.isTraceEnabled()) {
                log.trace("Matched path pattern [" + pathPattern + "] for requestURI [" + requestURI + "].  " +
                        "Utilizing corresponding filter chain...");
            }
            //這里好像看起來返回的是一個代理的過濾器!到底是不是?
            return filterChainManager.proxy(originalChain, pathPattern);
        }
    }

    return null;
}

這是配置的值,其會將請求的路徑和等號前面的路徑進行匹配。

mark

至此,整個獲取過濾器并執行的過程就結束了,接下來就是過濾器的具體執行了。

我們看return filterChainManager.proxy(originalChain, pathPattern);這句話,他返回的是一個代理過濾器??梢詮倪@里一步步跟蹤得到,他真實返回對象是:org.apache.shiro.web.servlet.ProxiedFilterChain。我們來看看他的doFilter方法:


public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
    if (this.filters == null || this.filters.size() == this.index) {
        //we've reached the end of the wrapped chain, so invoke the original one:
        if (log.isTraceEnabled()) {
            log.trace("Invoking original filter chain.");
        }
        this.orig.doFilter(request, response);
    } else {
        if (log.isTraceEnabled()) {
            log.trace("Invoking wrapped filter at index [" + this.index + "]");
        }
        this.filters.get(this.index++).doFilter(request, response, this);
    }
}

filters是一個集合,每執行完一個過濾器,索引就往后走一位,如果當前過濾器執行不通過,可以進行執行下一個過濾器,而this.filters.get(this.index++).doFilter(request, response, this);其實執行的還是org.apache.shiro.web.servlet.OncePerRequestFilter中的doFilter這個方法,周而復始,知道驗證成功,獲取全部失敗。

mark

從上圖可以看到,shiro給我們提供了很多默認的過濾器,我們平時用到的大部分都是繼承自org.apache.shiro.web.filter.AccessControlFilter。既然是一個過濾器,那么他最重要的當然是doFilter這個方法啦,跟蹤下發現,doFilter這個方法在:org.apache.shiro.web.servlet.OncePerRequestFilter這個方法的源碼,在前面已經貼出。

有點不同的是,這次,我們傳入的過濾器是org.apache.shiro.web.servlet.AdviceFilter這個類的子類實現,因此執行的會是這個類的doFilterInternal方法。


public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain)
            throws ServletException, IOException {

    Exception exception = null;

    try {
        //前置處理
        boolean continueChain = preHandle(request, response);
        if (log.isTraceEnabled()) {
            log.trace("Invoked preHandle method.  Continuing chain?: [" + continueChain + "]");
        }
        
        if (continueChain) {
            executeChain(request, response, chain);
        }
        //后置處理
        postHandle(request, response);
        if (log.isTraceEnabled()) {
            log.trace("Successfully invoked postHandle method");
        }

    } catch (Exception e) {
        exception = e;
    } finally {
        cleanup(request, response, exception);
    }
}

這個其實很簡單,就干了一件事,稍微封裝了一下這個過濾器的doFilter方法。其中boolean continueChain = preHandle(request, response);這句話是決定執行不執行這個filter的,但是當前類只是簡單的返回了一個true。這個類,好像沒有什么有意義的代碼。哈哈!這里我想大家可以猜到,這里的主要代碼都是在子類進一步進行實現的。由于我們是基于web應用的額,所以主要就看看org.apache.shiro.web.filter.PathMatchingFilter:

protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {

    if (this.appliedPaths == null || this.appliedPaths.isEmpty()) {
        if (log.isTraceEnabled()) {
            log.trace("appliedPaths property is null or empty.  This Filter will passthrough immediately.");
        }
        return true;
    }

    for (String path : this.appliedPaths.keySet()) {
        // If the path does match, then pass on to the subclass implementation for specific checks
        //(first match 'wins'):
        if (pathsMatch(path, request)) {
            log.trace("Current requestURI matches pattern '{}'.  Determining filter chain execution...", path);
            Object config = this.appliedPaths.get(path);
            return isFilterChainContinued(request, response, path, config);
        }
    }

    //no path matched, allow the request to go through:
    return true;
}

private boolean isFilterChainContinued(ServletRequest request, ServletResponse response,
                String path, Object pathConfig) throws Exception {

    if (isEnabled(request, response, path, pathConfig)) { //isEnabled check added in 1.2
        if (log.isTraceEnabled()) {
            log.trace("Filter '{}' is enabled for the current request under path '{}' with config [{}].  " +
                    "Delegating to subclass implementation for 'onPreHandle' check.",
                    new Object[]{getName(), path, pathConfig});
        }
        //The filter is enabled for this specific request, so delegate to subclass implementations
        //so they can decide if the request should continue through the chain or not:
        //這個是關鍵方法。但是當前類只返回了一個true,不用想肯定要看子類了!
        return onPreHandle(request, response, pathConfig);
    }

    if (log.isTraceEnabled()) {
        log.trace("Filter '{}' is disabled for the current request under path '{}' with config [{}].  " +
                "The next element in the FilterChain will be called immediately.",
                new Object[]{getName(), path, pathConfig});
    }
    //This filter is disabled for this specific request,
    //return 'true' immediately to indicate that the filter will not process the request
    //and let the request/response to continue through the filter chain:
    return true;
}

protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return true;
    }

接下來我們可以到org.apache.shiro.web.filter.AccessControlFilter看看onPreHandle這個方法的實現:


public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
    //執行isAccessAllowed和onAccessDenied這兩個方法;
    //由于||的特性,所以當isAccessAllowed返回false時才會執行onAccessDenied
    return isAccessAllowed(request, response, mappedValue) || onAccessDenied(request, response, mappedValue);
}
//交由子類進行實現
protected abstract boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception;

protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
    return onAccessDenied(request, response);
}

//交由子類進行實現    
protected abstract boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception;

至此,shiro的過濾器就差不多這樣了,我們在實際開發當中,可以繼承自AccessControlFilter這個方法,對isAccessAllowed,onAccessDenied這兩個方法進行實現即可。

《shiro源碼分析【整合spring】》(一)——Shiro初始化

《shiro源碼分析【整合spring】》(三)——Shiro驗證

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,885評論 6 541
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,312評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 177,993評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,667評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,410評論 6 411
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,778評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,775評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,955評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,521評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,266評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,468評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,998評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,696評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,095評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,385評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,193評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,431評論 2 378

推薦閱讀更多精彩內容