1. 程式人生 > >CAS:不攔截指定url過濾

CAS:不攔截指定url過濾

首先我們看一下我們客戶端中web.xml中的攔截器配置

    <filter>
        <filter-name>CASFilter</filter-name>
        <filter-class>org.jasig.cas.client.authentication.AuthenticationFilter</filter-class>
        <init-param>
            <param-name>casServerLoginUrl</param-name>
            <param-value
>
http://ssocas.ane56.com:8080/cas/login</param-value> </init-param> <init-param> <param-name>serverName</param-name> <param-value>http://ptl.ane56.com:8080</param-value> </init-param> </filter> <filter-mapping
>
<filter-name>CASFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

重要的操作無非就是客戶端jar包中的AuthenticationFilter,然後上網查了下,無非就是將這個攔截方法重寫。

反編譯一下

然後將該攔截器貼一下

package org.jasig.cas.client.authentication;

import java.io.IOException;
import javax.servlet.FilterChain;
import
javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.jasig.cas.client.util.AbstractCasFilter; import org.jasig.cas.client.util.CommonUtils; import org.jasig.cas.client.validation.Assertion; public class AuthenticationFilter extends AbstractCasFilter { private String casServerLoginUrl; private boolean renew = false; private boolean gateway = false; private GatewayResolver gatewayStorage = new DefaultGatewayResolverImpl(); protected void initInternal(FilterConfig filterConfig) throws ServletException { if (!isIgnoreInitConfiguration()) { super.initInternal(filterConfig); setCasServerLoginUrl(getPropertyFromInitParams(filterConfig, "casServerLoginUrl", null)); this.log.trace("Loaded CasServerLoginUrl parameter: " + this.casServerLoginUrl); setRenew(parseBoolean(getPropertyFromInitParams(filterConfig, "renew", "false"))); this.log.trace("Loaded renew parameter: " + this.renew); setGateway(parseBoolean(getPropertyFromInitParams(filterConfig, "gateway", "false"))); this.log.trace("Loaded gateway parameter: " + this.gateway); String gatewayStorageClass = getPropertyFromInitParams(filterConfig, "gatewayStorageClass", null); if (gatewayStorageClass != null) try { this.gatewayStorage = ((GatewayResolver)Class.forName(gatewayStorageClass).newInstance()); } catch (Exception e) { this.log.error(e, e); throw new ServletException(e); } } } public void init() { super.init(); CommonUtils.assertNotNull(this.casServerLoginUrl, "casServerLoginUrl cannot be null."); } public final void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)servletRequest; HttpServletResponse response = (HttpServletResponse)servletResponse; HttpSession session = request.getSession(false); Assertion assertion = session != null ? (Assertion)session.getAttribute("_const_cas_assertion_") : null; if (assertion != null) { filterChain.doFilter(request, response); return; } String serviceUrl = constructServiceUrl(request, response); String ticket = CommonUtils.safeGetParameter(request, getArtifactParameterName()); boolean wasGatewayed = this.gatewayStorage.hasGatewayedAlready(request, serviceUrl); if ((CommonUtils.isNotBlank(ticket)) || (wasGatewayed)) { filterChain.doFilter(request, response); return; } this.log.debug("no ticket and no assertion found"); String modifiedServiceUrl; String modifiedServiceUrl; if (this.gateway) { this.log.debug("setting gateway attribute in session"); modifiedServiceUrl = this.gatewayStorage.storeGatewayInformation(request, serviceUrl); } else { modifiedServiceUrl = serviceUrl; } if (this.log.isDebugEnabled()) { this.log.debug("Constructed service url: " + modifiedServiceUrl); } String urlToRedirectTo = CommonUtils.constructRedirectUrl(this.casServerLoginUrl, getServiceParameterName(), modifiedServiceUrl, this.renew, this.gateway); if (this.log.isDebugEnabled()) { this.log.debug("redirecting to \"" + urlToRedirectTo + "\""); } response.sendRedirect(urlToRedirectTo); } public final void setRenew(boolean renew) { this.renew = renew; } public final void setGateway(boolean gateway) { this.gateway = gateway; } public final void setCasServerLoginUrl(String casServerLoginUrl) { this.casServerLoginUrl = casServerLoginUrl; } public final void setGatewayStorage(GatewayResolver gatewayStorage) { this.gatewayStorage = gatewayStorage; } }

   我們重新定義一個類ReAuthenticationFilter,也繼承AbstractCasFilter類,在該類中完全複製AuthenticationFilter類中的內容,並在我們自己的攔截器做如下修改:

 1.增加excepPaths屬性,用於存放要排除過濾的路徑,採用陣列方式存放,應對多個url頭的攔截。

private String[] excludePaths;

 2.修改initInternal方法、從web.xml配置中解析出要排除過濾的路徑

 protected void initInternal(final FilterConfig filterConfig) throws ServletException {
        if (!isIgnoreInitConfiguration()) {
            super.initInternal(filterConfig);
            setCasServerLoginUrl(getPropertyFromInitParams(filterConfig, "casServerLoginUrl", null));
            log.trace("Loaded CasServerLoginUrl parameter: " + this.casServerLoginUrl);
            setRenew(parseBoolean(getPropertyFromInitParams(filterConfig, "renew", "false")));
            log.trace("Loaded renew parameter: " + this.renew);
            setGateway(parseBoolean(getPropertyFromInitParams(filterConfig, "gateway", "false")));
            log.trace("Loaded gateway parameter: " + this.gateway);
            final String gatewayStorageClass = getPropertyFromInitParams(filterConfig, "gatewayStorageClass", null);
            if (gatewayStorageClass != null) {
                try {
                    this.gatewayStorage = (GatewayResolver) Class.forName(gatewayStorageClass).newInstance();
                } catch (final Exception e) {
                    log.error(e,e);
                    throw new ServletException(e);
                }
            }


            //攔截器過濾修改************begin*************************
            String _excludePaths = getPropertyFromInitParams(filterConfig, "excepPaths", null);
            if(CommonUtils.isNotBlank(_excludePaths)){
             setExcludePaths(_excludePaths.trim().split(","));
            }
            //攔截器過濾修改************end************************
        }
    }

 3.修改doFilter方法、判斷請求路徑是否需要過濾

    public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) servletRequest;
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        final HttpSession session = request.getSession(false);
        final Assertion assertion = session != null ? (Assertion) session.getAttribute(CONST_CAS_ASSERTION) : null;


        //攔截器過濾修改************begin********************
        boolean isAir = request.getParameter("isAir")!=null && "true".equals(request.getParameter("isAir"));
        if (isAir ) {
            filterChain.doFilter(request, response);
        }

        String uri = request.getRequestURI()+request.getQueryString;
        boolean isInWhiteList = false;
        if(excludePaths!=null && excludePaths.length>0 && uri!=null){
            for(String path : excludePaths){
             if(CommonUtils.isNotBlank(path)){
              isInWhiteList = uri.indexOf(path.trim())>-1;
               if(isInWhiteList){
                 break;
               }
              }
            }
        }
        
        if(isInWhiteList){
            filterChain.doFilter(request, response);
            return;
           }
        //攔截器過濾修改************end********************************
        
        if (assertion != null) {
            filterChain.doFilter(request, response);
            return;
        }
        final String serviceUrl = constructServiceUrl(request, response);
        final String ticket = CommonUtils.safeGetParameter(request,getArtifactParameterName());
        final boolean wasGatewayed = this.gatewayStorage.hasGatewayedAlready(request, serviceUrl);
        if (CommonUtils.isNotBlank(ticket) || wasGatewayed) {
            filterChain.doFilter(request, response);
            return;
        }
        final String modifiedServiceUrl;
        log.debug("no ticket and no assertion found");
        if (this.gateway) {
            log.debug("setting gateway attribute in session");
            modifiedServiceUrl = this.gatewayStorage.storeGatewayInformation(request, serviceUrl);
        } else {
            modifiedServiceUrl = serviceUrl;
        }
        if (log.isDebugEnabled()) {
            log.debug("Constructed service url: " + modifiedServiceUrl);
        }
        final String urlToRedirectTo = CommonUtils.constructRedirectUrl(this.casServerLoginUrl, getServiceParameterName(), modifiedServiceUrl, this.renew, this.gateway);
        if (log.isDebugEnabled()) {
            log.debug("redirecting to \"" + urlToRedirectTo + "\"");
        }
        response.sendRedirect(urlToRedirectTo);
    }

   4.修改完以上方法、則web.xml中還需要修改兩點,修改後的web.xml配置如下:

    <filter>
        <filter-name>CASFilter</filter-name>
        <filter-class>org.jasig.cas.client.authentication.ReAuthenticationFilter</filter-class>
        <init-param>
            <param-name>casServerLoginUrl</param-name>
            <param-value>http://ssocas.ane56.com:8080/cas/login</param-value>
        </init-param>
        <init-param>
            <param-name>serverName</param-name>
            <param-value>http://ptl.ane56.com:8080</param-value>
        </init-param>
        <init-param>
           <description>cas not filter url</description>
           <param-name>exceptPaths</param-name>
           <param-value>isAir=true,/user/login</param-value>
        </init-param>
    </filter>

慣例圖示

從request獲取各種路徑總結 
request.getRealPath("url"); // 虛擬目錄對映為實際目錄


request.getRealPath("./");    // 網頁所在的目錄

request.getRealPath("../"); // 網頁所在目錄的上一層目錄

request.getContextPath();    // 應用的web目錄的名稱


http://localhost:7001/bookStore/ 
/bookStore/ => [contextPath] (request.getContextPath())

獲取Web專案的全路徑 
String strDirPath = request.getSession().getServletContext().getRealPath("/");

以工程名為TEST為例:

(1)得到包含工程名的當前頁面全路徑:request.getRequestURI() 
結果:/TEST/test.jsp


(2)得到工程名:request.getContextPath() 
結果:/TEST


(3)得到當前頁面所在目錄下全名稱:request.getServletPath() 
結果:如果頁面在jsp目錄下 /TEST/jsp/test.jsp


(4)得到頁面所在伺服器的全路徑:application.getRealPath("頁面.jsp") 
結果:D:\resin\webapps\TEST\test.jsp


(5)得到頁面所在伺服器的絕對路徑:absPath=new java.io.File(application.getRealPath(request.getRequestURI())).getParent(); 
結果:D:\resin\webapps\TEST

2.在類中取得路徑:

(1)類的絕對路徑:Class.class.getClass().getResource("/").getPath() 
結果:/D:/TEST/WebRoot/WEB-INF/classes/pack/


(2)得到工程的路徑:System.getProperty("user.dir") 
結果:D:\TEST

3.在Servlet中取得路徑:

(1)得到工程目錄:request.getSession().getServletContext().getRealPath("") 引數可具體到包名。 
結果:E:\Tomcat\webapps\TEST


(3)得到相對地址:request.getRequestURI() 
結果:/TEST/test

相關推薦

CAS攔截指定url過濾

首先我們看一下我們客戶端中web.xml中的攔截器配置 <filter> <filter-name>CASFilter</filter-name> <filter-class>org.jas

SpringBoot2.x攔截器會攔截static目錄下的靜態資源解決與攔截指定目錄

一、不攔截static目錄下的檔案  目錄如下 瀏覽器訪問直接訪問js檔案會被攔截,這時在攔截器添的excludePathPatterns方法增加“/js/**”,這樣子就不會被攔截了。程式碼如下 @Override public void addInterce

springmvc攔截器,設定攔截URL

對於springmvc,有兩種方式配置攔截器。 一是實現HandlerInterceptor介面,如 publicclass MyInterceptor1 implements HandlerInterceptor {       //該方法在action執行前執行,可以實現對資料的預處理,  

springmvc配置攔截url

</pre><span style="font-size:18px;">在這裡要使用 <mvc:exclude-mapping path="/hello.html" /> 但是有時候 會報<span style="color: rg

springmvc的攔截器,怎麼設定攔截url

在攔截器裡注入一個屬性 List<String> uncheckUrls <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.hz.sunday.portalvip.interceptor.Perm

fiddler filters 使用(fiddler只顯示指定請求,fiddler顯示指定請求,即filter請求過濾)轉自http://blog.csdn.net/notejs/article/

fiddler filters 使用(fiddler只顯示指定請求,fiddler不顯示指定請求,即filter請求過濾)Fiddler 有一個filters可以很好的幫助我們只顯示我們關係的請求或者隱藏掉我們不關心的請求。這在開發中是非常有用的,尤其是你在這邊想看請求,那邊

vs2013新建MVC項目時提示系統找指定文件(異常來自HRESULT0x80070002)

描述 studio ack 對話框 asp.net vs2013 提示 系統找不到指定文件 uget 一.問題描述 1.打開vs2013,選擇”文件|新建|項目”,彈出如下對話框。 2.點擊左側的“Web”,選擇“ASP.NET Web 應用程序”,點擊確定

Latex排版CTeX winEdit 輸出“系統找指定的文件”的解決辦法)

排版 可執行文件 程序 而不是 安裝 span 解決 inf html winEdit輸出“系統找不到指定的文件”,這裏“指定的文件”是“TeXify.exe”等需要運行的程序,而不是當前需要編譯的“.tex”文件。所以,問題的本質就是系統找不到“TeXify.ex

SVN提交文件失敗系統找指定路徑

svn 系統找不到指定路徑 完成程序代碼工作後,進行SVN的文件提交。先進行項目的更新,然後在修改的文件上進行提交操作,發現SVN彈出提示信息,“系統找不到指定路徑”提交失敗. 解決方案 通過cleanup解決了問題提供另外的一個可能的方案出現這個問題的原因是,在.svn目錄中缺少一個叫做tm

fiddler filters 使用(fiddler只顯示指定請求,fiddler顯示指定請求,即filter請求過濾)(轉)

alt 正則 完全 字符 真的 upload 比較 left 模塊化 fiddler filters 使用(fiddler只顯示指定請求,fiddler不顯示指定請求,即filter請求過濾) Fiddler 有一個filters可以很好的幫助我們只顯示我們關系的請求或者隱

win 8系統System.IO.FileNotFoundException: 未能加載文件或程序集“CefSharp.Core.dll”或它的某一個依賴項。找指定的模塊

正常 下載地址 except sharp 未能加載 虛擬 pac 報錯 exce 最近用CefSharp做了一個chrome核心的瀏覽器。 在win 7、win 10系統上都正常運行,但是在win 8系統上報錯了。 win 8系統:System.IO.FileNotFoun

處理新建信任能繼續,因為聯系指定的域

dea 正常 img ces 圖片 lte com col 繼續 最近在做二個域的合並,DNS解析建好後,在創建信任時,出現錯誤,如下圖 使用 nltest /dsgetdc:域名,命令查詢,問題出在DNS解析上,下圖為解析不到的錯誤圖示: 處理,在 DNS 管理器,點擊畫

python setup.py install 報錯error: [WinError 3] 系統找指定的路徑。: 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\PlatformSDK\\lib

Outline 在通過 setup.py 安裝python模組時,遇到了以下報錯: # 執行 python setup.py install # 報錯: error: [WinError 3] 系統找不到指定的路徑。: 'C:\\Program Files (x86)\\Microsof

Maven項目pom.xml文件報xxx argetm2e-wtpweb-resourcesMETA-INFMANIFEST.MF (系統找指定的路徑。) 問題

對話框 pom style java 錯誤 pom.xml tar resources col 1、問題現象:   在Maven項目中的pom.xml文件的第一行:D:\learn\Java\eclipse-jee-mars-2-win32_x64\eclipse-wor

Mysql資料庫無法啟動,系統找指定檔案

一、資料庫無法啟動 新程式部署,將mysql資料夾直接拷過去,進入bin目錄,點選mysqlld.exe,開啟navicat工具提示無法連線: 原因 任務管理中檢視沒有mysql程序,mysql未正常啟動; 解決 將mysql資料夾下的data目錄刪除 wi

使用shutil.copyfile遇到錯誤[WinError 3] 系統找指定的路徑。

程式shutil.copyfile(os.path.join(sourcepath+'/'+eachclass+ '/',im),valpath+'/'+eachclass+'/'+im) 出現錯誤:[WinError 3] 系統找不到指定的路徑。 分析:路徑裡面的im是

xgboost問題OsError: WinError 126 找指定模組

import xgboost出現下面的問題: OsError: WinError 126 找不到指定模組 那麼我的解決辦法是下一個MinGW-w64 mingw下載地址 最後一定要記得新增下載的mingw的環境變數 比如: C:\Program Files\mingw-

王權富貴安裝OpenCV匯入的時候出現DLL load failed指定模組 or %1是有效的32位程式

問題:   網上找了好多方法 (1)版本不匹配(失敗) (2)安裝microsoft Visual C++ distributed 2015 X64(失敗) (3)升級window10(沒有嘗試) (3)複製什麼什麼檔案到什麼什麼目錄下(失敗) (4)ht

虛擬機器提示無法開啟核心裝置“\\.\Global\vmx86”: 系統找指定的檔案

Win 10 vmware12 無法開啟核心裝置“\\.\Global\vmx86”: 系統找不到指定的檔案。你想要在安裝 VMware Workstation 前重啟嗎? 開啟vmware12後出現核心錯誤,查了一下,在自己的win10下面應該是如下的解決方法: 1. 找到

Import TensorFlow as tf 報錯ImportError: DLL load failed: 找指定的程式

一、報錯描述 今天在新電腦上安裝TensorFlow環境,遇到一個小問題。當使用pip工具或在Pycharm中自動安裝完TensorFlow後,在程式中匯入竟然報錯了: import tensorflow as tf 如此簡單的一句匯入竟然報錯,Why。具體錯誤如下,主要是Imp