關於cas-client單點登錄客戶端攔截請求和忽略/排除不需要攔截的請求URL的問題(不需要修改任何代碼,只需要一個配置)


前言:今天在網上無意間看到cas單點登錄排除請求的問題,發現很多人在討論如何通過改寫AuthenticationFilter類來實現忽略/排除請求URL的功能;突發奇想搜了一下,還真蠻多人都是這么干的,原諒我是個耿直的boy,當時我笑的飯都噴出來了,只需要一個配置的問題,被你們搞的這么麻煩;雖然很想回復他們“你們這幫人用別人的東西都不看源碼的嗎?”,轉念一想,這也要怪作者不給力,文檔里壓根沒有提到這個配置,在這里用少量篇幅講解如何配置排除不需要攔截的請求URL,后面用大量篇幅介紹我是如何從源碼中得知這個配置的,希望對大家有用!做好自己!--eguid始終堅持原創的開源技術文章分享,博客園與本博客保持同步更新。歡迎大家加群一起交流:608423839

1、cas-client單點登錄配置

http://blog.csdn.net/eguid_1/article/details/51278622,cas-client完整配置。

沒有實現忽略/排除請求URL的cas-client登錄驗證過濾器

 

[html]  view plain  copy
 
 print?
  1. <filter>    
  2.       <filter-name>casAuthenticationFilter</filter-name>    
  3.    <filter-class>org.jasig.cas.client.authentication.AuthenticationFilter</filter-class>    
  4.       <init-param>    
  5.          <param-name>casServerLoginUrl</param-name>    
  6.          <param-value>https://cas.eguid.cc/cas-server/</param-value>    
  7.       </init-param>    
  8.       <init-param>    
  9.          <param-name>serverName</param-name>    
  10.          <param-value>http://client.eguid.cc/</param-value>    
  11.       </init-param>    
  12.    </filter>    
  13.    <filter-mapping>    
  14.       <filter-name>casAuthenticationFilter</filter-name>    
  15.       <url-pattern>/*</url-pattern>    
  16.    </filter-mapping>    


這個配置依然是可用的,當然我們要實現忽略/排除請求URL的功能,那么我們該怎么做呢?

 

2、忽略/排除多個請求URL

 

[html]  view plain  copy
 
 print?
  1. <filter>  
  2.      <filter-name>casAuthenticationFilter</filter-name>  
  3.   <filter-class>org.jasig.cas.client.authentication.AuthenticationFilter</filter-class>  
  4.      <init-param>  
  5.         <param-name>casServerLoginUrl</param-name>  
  6.         <param-value>http://cas.eguid.cc/cas-server/</param-value>  
  7.      </init-param>  
  8.      <init-param>  
  9.         <param-name>serverName</param-name>  
  10.         <param-value>http://cilent.eguid.cc/</param-value>  
  11.         <param-name>ignorePattern</param-name>  
  12.         <param-value>/js/*|/img/*|/view/*|/css/*</param-value>  
  13.      </init-param>  
  14.   </filter><!--做好自己!eguid原創-->  
  15.   <filter-mapping>  
  16.      <filter-name>casAuthenticationFilter</filter-name>  
  17.      <url-pattern>/*</url-pattern>  
  18.   </filter-mapping>  


如上所見,我們排除了四個請求URL(必須是正則表達式形式,下面會講為什么要這么配置)

 

3、cas-client默認登錄驗證過濾器源碼解析

看源碼,一定要帶着目的去看;我們的目的就是找AuthenticationFilter這個cas-client默認登錄驗證過濾器是否具有排除登錄請求URL的功能。

(1)打開cas-client項目源碼

打開github上的cas-client項目,可以把項目導到本地或者直接在github上找到org.jasig.cas.client.authentication.AuthenticationFilter.Java這個類。

(2)登錄驗證過濾器AuthenticationFilter的doFilter

既然是個過濾器,就直接找到該類的doFilter方法

 

[java]  view plain  copy
 
 print?
  1. <span style="color:#24292e;">   public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,  
  2.             final FilterChain filterChain) throws IOException, ServletException {  
  3.         <!--做好自己!eguid原創-->  
  4.         final HttpServletRequest request = (HttpServletRequest) servletRequest;  
  5.         final HttpServletResponse response = (HttpServletResponse) servletResponse;  
  6.           
  7.         if (</span><span style="color:#ff0000;">isRequestUrlExcluded</span><span style="color:#24292e;">(request)) {  
  8.             logger.debug("Request is ignored.");  
  9.             filterChain.doFilter(request, response);  
  10.             return;  
  11.         }  
  12.           
  13.         final HttpSession session = request.getSession(false);  
  14.         final Assertion assertion = session != null ? (Assertion) session.getAttribute(CONST_CAS_ASSERTION) : null;  
  15.   
  16.         if (assertion != null) {  
  17.             filterChain.doFilter(request, response);  
  18.             return;  
  19.         }  
  20.   
  21.         final String serviceUrl = constructServiceUrl(request, response);  
  22.         final String ticket = retrieveTicketFromRequest(request);  
  23.         final boolean wasGatewayed = this.gateway && this.gatewayStorage.hasGatewayedAlready(request, serviceUrl);  
  24.   
  25.         if (CommonUtils.isNotBlank(ticket) || wasGatewayed) {  
  26.             filterChain.doFilter(request, response);  
  27.             return;  
  28.         }  
  29.   
  30.         final String modifiedServiceUrl;  
  31.   
  32.         logger.debug("no ticket and no assertion found");  
  33.         if (this.gateway) {  
  34.             logger.debug("setting gateway attribute in session");  
  35.             modifiedServiceUrl = this.gatewayStorage.storeGatewayInformation(request, serviceUrl);  
  36.         } else {  
  37.             modifiedServiceUrl = serviceUrl;  
  38.         }  
  39.   
  40.         logger.debug("Constructed service url: {}", modifiedServiceUrl);  
  41.   
  42.         final String urlToRedirectTo = CommonUtils.constructRedirectUrl(this.casServerLoginUrl,  
  43.                 getProtocol().getServiceParameterName(), modifiedServiceUrl, this.renew, this.gateway);  
  44.   
  45.         logger.debug("redirecting to \"{}\"", urlToRedirectTo);  
  46.         this.authenticationRedirectStrategy.redirect(request, response, urlToRedirectTo);  
  47.     }</span>  

 

(3)isRequestUrlExcluded方法

 

第一眼就看到了上面代碼紅色標識處的isRequestUrlExcluded,這個意思很直白,判斷是不是需要忽略/排除的請求URL。

繼續接着找到isRequestUrlExcluded這個方法的實現代碼:

 

[java]  view plain  copy
 
 print?
  1. <span style="color:#24292e;"> private boolean isRequestUrlExcluded(final HttpServletRequest request) {  
  2.         if (this.ignoreUrlPatternMatcherStrategyClass == null) {  
  3.             return false;  
  4.         }  
  5.         <!--做好自己!eguid原創-->  
  6.         final StringBuffer urlBuffer = request.getRequestURL();  
  7.         if (request.getQueryString() != null) {  
  8.             urlBuffer.append("?").append(request.getQueryString());  
  9.         }  
  10.         final String requestUri = urlBuffer.toString();  
  11.         return this.</span><span style="color:#ff0000;">ignoreUrlPatternMatcherStrategyClass</span><span style="color:#24292e;">.matches(requestUri);  
  12.     }</span>  

看紅色標識位置的名字,這里用到了UrlPatternMatcherStrategy這個類,意思很簡單直白:‘請求url的匹配策略類’,暫時還不知道這里是正則匹配,往后看:

 

(4)請求URL的匹配策略類UrlPatternMatcherStrategy

 

[java]  view plain  copy
 
 print?
  1. private UrlPatternMatcherStrategy ignoreUrlPatternMatcherStrategyClass = null;  

發現該類是在初始化方法中進行初始化的:

 

 

[java]  view plain  copy
 
 print?
  1. <span style="color:#24292e;"> protected void initInternal(final FilterConfig filterConfig) throws ServletException {  
  2.         if (!isIgnoreInitConfiguration()) {  
  3.             super.initInternal(filterConfig);  
  4.             setCasServerLoginUrl(getString(ConfigurationKeys.CAS_SERVER_LOGIN_URL));  
  5.             setRenew(getBoolean(ConfigurationKeys.RENEW));  
  6.             setGateway(getBoolean(ConfigurationKeys.GATEWAY));  
  7.              <!--做好自己!eguid原創-->            
  8.             final String ignorePattern = getString(ConfigurationKeys.</span><span style="color:#ff0000;">IGNORE_PATTERN</span><span style="color:#24292e;">);  
  9.             final String ignoreUrlPatternType = getString(ConfigurationKeys.</span><span style="color:#ff0000;">IGNORE_URL_PATTERN_TYPE</span><span style="color:#24292e;">);  
  10.               
  11.             if (ignorePattern != null) {  
  12.                 final Class<? extends UrlPatternMatcherStrategy> ignoreUrlMatcherClass = PATTERN_MATCHER_TYPES.get(ignoreUrlPatternType);  
  13.                 if (ignoreUrlMatcherClass != null) {  
  14.                     this.ignoreUrlPatternMatcherStrategyClass = ReflectUtils.newInstance(ignoreUrlMatcherClass.getName());  
  15.                 } else {  
  16.                     try {  
  17.                         logger.trace("Assuming {} is a qualified class name...", ignoreUrlPatternType);  
  18.                         this.ignoreUrlPatternMatcherStrategyClass = ReflectUtils.newInstance(ignoreUrlPatternType);  
  19.                     } catch (final IllegalArgumentException e) {  
  20.                         logger.error("Could not instantiate class [{}]", ignoreUrlPatternType, e);  
  21.                     }  
  22.                 }  
  23.                 if (this.ignoreUrlPatternMatcherStrategyClass != null) {  
  24.                     this.ignoreUrlPatternMatcherStrategyClass.setPattern(ignorePattern);  
  25.                 }  
  26.             }  
  27.               
  28.             final Class<? extends GatewayResolver> gatewayStorageClass = getClass(ConfigurationKeys.GATEWAY_STORAGE_CLASS);  
  29.   
  30.             if (gatewayStorageClass != null) {  
  31.                 setGatewayStorage(ReflectUtils.newInstance(gatewayStorageClass));  
  32.             }  
  33.               
  34.             final Class<? extends AuthenticationRedirectStrategy> authenticationRedirectStrategyClass = getClass(ConfigurationKeys.AUTHENTICATION_REDIRECT_STRATEGY_CLASS);  
  35.   
  36.             if (authenticationRedirectStrategyClass != null) {  
  37.                 this.authenticationRedirectStrategy = ReflectUtils.newInstance(authenticationRedirectStrategyClass);  
  38.             }  
  39.         }  
  40.     }</span>  

雖然使用了反射,但是依然不影響我們找到根本所在,找到ConfigurationKeys這個類里面的變量究竟是什么:

 

 

[java]  view plain  copy
 
 print?
  1. <span style="color:#24292e;">   ConfigurationKey<String> IGNORE_PATTERN = new ConfigurationKey<String>("</span><span style="color:#ff0000;">ignorePattern</span><span style="color:#24292e;">", null);  
  2.     ConfigurationKey<String> IGNORE_URL_PATTERN_TYPE = new ConfigurationKey<String>("</span><span style="color:#ff0000;">ignoreUrlPatternType</span><span style="color:#24292e;">", "REGEX");</span>  

字面上理解這兩個常量定義了忽略模式以及忽略模式類型是‘正則’,當然我們還是不確定是不是正則,那么繼續往下找

 

 

[java]  view plain  copy
 
 print?
  1. final Class<? extends UrlPatternMatcherStrategy> ignoreUrlMatcherClass = PATTERN_MATCHER_TYPES.get(ignoreUrlPatternType);  

 

我們已經通過ConfigurationKeys類知道ignoreUrlPatternType是個‘REGEX’字符串,那么

 

[java]  view plain  copy
 
 print?
  1. PATTERN_MATCHER_TYPES.put("REGEX", RegexUrlPatternMatcherStrategy.class);  

那么按照REGEX對應的值找到RegexUrlPatternMatcherStrategy這個類:

 

(5)確定RegexUrlPatternMatcherStrategy類用於處理正則驗證匹配

 

[java]  view plain  copy
 
 print?
  1. public final class RegexUrlPatternMatcherStrategy implements UrlPatternMatcherStrategy {  
  2. <!--做好自己!eguid原創-->  
  3.     private Pattern pattern;  
  4.   
  5.     public RegexUrlPatternMatcherStrategy() {}  
  6.   
  7.     public RegexUrlPatternMatcherStrategy(final String pattern) {  
  8.         this.setPattern(pattern);  
  9.     }  
  10.       
  11.     public boolean matches(final String url) {  
  12.         return this.pattern.matcher(url).find();  
  13.     }  
  14.   
  15.     public void setPattern(final String pattern) {  
  16.         this.pattern = Pattern.compile(pattern);  
  17.     }  
  18. }  

該類中用到了Pattern來編譯和匹配正則表達式

 

到這里我們終於可以確定可以用ignorePattern來忽略/排除我們不需要攔截的請求URL,當然必須滿足正則表達式。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM