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

二、Shiro過濾器

由于我們的分析只是基于web項(xiàng)目的竭宰,由配置文件我們可以知道空郊,在web項(xiàng)目中,shiro的入口是一個(gè)Filter類切揭。至于filter的初始化狞甚,在第一部分已經(jīng)介紹,接下來我們直接來看該過濾器是如何工作的廓旬。
由于集成spring的哼审,這個(gè)filter的具體實(shí)現(xiàn)類是:org.apache.shiro.spring.web.ShiroFilterFactoryBean.SpringShiroFilter。這是一個(gè)內(nèi)部類嗤谚。這個(gè)類繼承自:org.apache.shiro.web.servlet.AbstractShiroFilter,整個(gè)過濾器的核心處理方法都是在這個(gè)類實(shí)現(xiàn)的怔蚌,而SpringShiroFilter只是做了一些初始化的工作巩步,具體可以看源碼:


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

我們都知道一個(gè)過濾器的核心就是doFilter方法,SpringShiroFilter這個(gè)類的doFilter方法的實(shí)現(xiàn)是由其父類:org.apache.shiro.web.servlet.OncePerRequestFilter實(shí)現(xiàn)的桦踊。下面來看看這個(gè)doFilter方法的具體實(shí)現(xiàn)椅野。


public final void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
    String alreadyFilteredAttributeName = getAlreadyFilteredAttributeName();
    //判斷當(dāng)前過濾器是否已經(jīng)執(zhí)行,如果已經(jīng)執(zhí)行則不進(jìn)行任何操作
    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 {
        // 在這里啟動(dòng)過濾器
        log.trace("Filter '{}' not yet executed.  Executing now.", getName());
        // 注意:這里將當(dāng)前的過濾器名字進(jìn)行存儲(chǔ)
        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);
        }
    }
}

由上面可以看到真正對(duì)請(qǐng)求進(jìn)行過處理的方法時(shí)doFilterInternal這個(gè)方法籍胯。我們直接貼源碼竟闪。


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);
        //這里其實(shí)就是初始化一個(gè)全局的subject對(duì)象≌壤牵可以在任何地方進(jìn)行獲取炼蛤。
        final Subject subject = createSubject(request, response);
        
        //這一步是主要的處理,有興趣的可以繼續(xù)跟蹤下代碼蝶涩,這里其實(shí)就是執(zhí)行回調(diào)里面的方法理朋。
        subject.execute(new Callable() {
            public Object call() throws Exception {
                //看名字就知道這里不重要啦,哈哈绿聘!
                updateSessionLastAccessTime(request, response);
                //這個(gè)是關(guān)鍵
                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);
    }
}

上面的代碼中嗽上,關(guān)鍵的就是的一個(gè)方法是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;
    }
    
    //獲取當(dāng)前請(qǐng)求的相對(duì)路徑
    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
    //這個(gè)循環(huán)就是一個(gè)匹配的過程將當(dāng)前路徑與配置的路徑進(jìn)行比較兽愤,根據(jù)配置轉(zhuǎn)發(fā)到想應(yīng)的過濾器。
    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...");
            }
            //這里好像看起來返回的是一個(gè)代理的過濾器挪圾!到底是不是浅萧?
            return filterChainManager.proxy(originalChain, pathPattern);
        }
    }

    return null;
}

這是配置的值,其會(huì)將請(qǐng)求的路徑和等號(hào)前面的路徑進(jìn)行匹配哲思。

mark

至此惯殊,整個(gè)獲取過濾器并執(zhí)行的過程就結(jié)束了,接下來就是過濾器的具體執(zhí)行了也殖。

我們看return filterChainManager.proxy(originalChain, pathPattern);這句話土思,他返回的是一個(gè)代理過濾器务热。可以從這里一步步跟蹤得到己儒,他真實(shí)返回對(duì)象是: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是一個(gè)集合,每執(zhí)行完一個(gè)過濾器闪湾,索引就往后走一位冲甘,如果當(dāng)前過濾器執(zhí)行不通過,可以進(jìn)行執(zhí)行下一個(gè)過濾器途样,而this.filters.get(this.index++).doFilter(request, response, this);其實(shí)執(zhí)行的還是org.apache.shiro.web.servlet.OncePerRequestFilter中的doFilter這個(gè)方法江醇,周而復(fù)始,知道驗(yàn)證成功何暇,獲取全部失敗陶夜。

mark

從上圖可以看到,shiro給我們提供了很多默認(rèn)的過濾器裆站,我們平時(shí)用到的大部分都是繼承自org.apache.shiro.web.filter.AccessControlFilter条辟。既然是一個(gè)過濾器,那么他最重要的當(dāng)然是doFilter這個(gè)方法啦宏胯,跟蹤下發(fā)現(xiàn)羽嫡,doFilter這個(gè)方法在:org.apache.shiro.web.servlet.OncePerRequestFilter這個(gè)方法的源碼,在前面已經(jīng)貼出肩袍。

有點(diǎn)不同的是杭棵,這次,我們傳入的過濾器是org.apache.shiro.web.servlet.AdviceFilter這個(gè)類的子類實(shí)現(xiàn)氛赐,因此執(zhí)行的會(huì)是這個(gè)類的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);
    }
}

這個(gè)其實(shí)很簡(jiǎn)單,就干了一件事鹰祸,稍微封裝了一下這個(gè)過濾器的doFilter方法甫窟。其中boolean continueChain = preHandle(request, response);這句話是決定執(zhí)行不執(zhí)行這個(gè)filter的,但是當(dāng)前類只是簡(jiǎn)單的返回了一個(gè)true蛙婴。這個(gè)類粗井,好像沒有什么有意義的代碼。哈哈街图!這里我想大家可以猜到浇衬,這里的主要代碼都是在子類進(jìn)一步進(jìn)行實(shí)現(xiàn)的。由于我們是基于web應(yīng)用的額餐济,所以主要就看看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:
        //這個(gè)是關(guān)鍵方法耘擂。但是當(dāng)前類只返回了一個(gè)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這個(gè)方法的實(shí)現(xiàn):


public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
    //執(zhí)行isAccessAllowed和onAccessDenied這兩個(gè)方法醉冤;
    //由于||的特性秩霍,所以當(dāng)isAccessAllowed返回false時(shí)才會(huì)執(zhí)行onAccessDenied
    return isAccessAllowed(request, response, mappedValue) || onAccessDenied(request, response, mappedValue);
}
//交由子類進(jìn)行實(shí)現(xiàn)
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);
}

//交由子類進(jìn)行實(shí)現(xiàn)    
protected abstract boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception;

至此,shiro的過濾器就差不多這樣了蚁阳,我們?cè)趯?shí)際開發(fā)當(dāng)中铃绒,可以繼承自AccessControlFilter這個(gè)方法,對(duì)isAccessAllowed螺捐,onAccessDenied這兩個(gè)方法進(jìn)行實(shí)現(xiàn)即可颠悬。

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

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市定血,隨后出現(xiàn)的幾起案子赔癌,更是在濱河造成了極大的恐慌,老刑警劉巖澜沟,帶你破解...
    沈念sama閱讀 211,639評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件灾票,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡倔喂,警方通過查閱死者的電腦和手機(jī)铝条,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,277評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門靖苇,熙熙樓的掌柜王于貴愁眉苦臉地迎上來席噩,“玉大人,你說我怎么就攤上這事贤壁〉渴啵” “怎么了?”我有些...
    開封第一講書人閱讀 157,221評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵脾拆,是天一觀的道長(zhǎng)馒索。 經(jīng)常有香客問我,道長(zhǎng)名船,這世上最難降的妖魔是什么绰上? 我笑而不...
    開封第一講書人閱讀 56,474評(píng)論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮渠驼,結(jié)果婚禮上蜈块,老公的妹妹穿的比我還像新娘。我一直安慰自己迷扇,他們只是感情好百揭,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,570評(píng)論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著蜓席,像睡著了一般器一。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上厨内,一...
    開封第一講書人閱讀 49,816評(píng)論 1 290
  • 那天祈秕,我揣著相機(jī)與錄音渺贤,去河邊找鬼。 笑死踢步,一個(gè)胖子當(dāng)著我的面吹牛癣亚,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播获印,決...
    沈念sama閱讀 38,957評(píng)論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼述雾,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了兼丰?” 一聲冷哼從身側(cè)響起玻孟,我...
    開封第一講書人閱讀 37,718評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎鳍征,沒想到半個(gè)月后黍翎,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,176評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡艳丛,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,511評(píng)論 2 327
  • 正文 我和宋清朗相戀三年匣掸,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片氮双。...
    茶點(diǎn)故事閱讀 38,646評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡碰酝,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出戴差,到底是詐尸還是另有隱情送爸,我是刑警寧澤,帶...
    沈念sama閱讀 34,322評(píng)論 4 330
  • 正文 年R本政府宣布暖释,位于F島的核電站袭厂,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏球匕。R本人自食惡果不足惜纹磺,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,934評(píng)論 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望亮曹。 院中可真熱鬧橄杨,春花似錦、人聲如沸乾忱。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,755評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽窄瘟。三九已至衷佃,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間蹄葱,已是汗流浹背氏义。 一陣腳步聲響...
    開封第一講書人閱讀 31,987評(píng)論 1 266
  • 我被黑心中介騙來泰國(guó)打工锄列, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人惯悠。 一個(gè)月前我還...
    沈念sama閱讀 46,358評(píng)論 2 360
  • 正文 我出身青樓邻邮,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親克婶。 傳聞我的和親對(duì)象是個(gè)殘疾皇子筒严,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,514評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容