Apache CXF自定義攔截器實現權限控制

jopen 10年前發布 | 80K 次閱讀 WEB服務/RPC/SOA Apache CXF

一. 攔截器

在我們學習Java的征途中碰到了很多攔截器: Servlet中的Filter就是一個攔截器, Struts2中也有攔截器,.

CXF中的攔截器其基本原理還是使用動態代理, 我們可以在不對核心模塊進行修改的情況下, 動態添加一些功能, 從而降低代碼的耦合性.


二. CXF攔截器

CXF通過在Interceptor中對消息進行特殊處理, 實現了很多重要功能模塊, 例如: 日志記錄, soap消息處理, 消息的壓縮處理.

下面我們使用一個例子介紹CXF Log攔截器: 

1. 服務端添加日志攔截器:

    public class MyServer {  
        public static void main(String[] args) {  
            HelloService helloService = new HelloServiceImpl();  
            EndpointImpl epi = (EndpointImpl)Endpoint.publish("http://localhost/sayHello", helloService);  
            epi.getInInterceptors().add(new LoggingInInterceptor()); // 添加服務器端in log攔截器  
            epi.getOutInterceptors().add(new LoggingOutInterceptor()); // 添加服務器端out log攔截器  
            System.out.println("Web Service 暴露成功");  
        }  
    }  
</div> </div>

2. 客戶端添加日志攔截器

    public class MyClient {
public static void main(String[] args) {
HelloServiceImplService factory = new HelloServiceImplService();
HelloService helloService = factory.getHelloServiceImplPort();

        Client client = ClientProxy.getClient(helloService);  
        client.getInInterceptors().add(new LoggingInInterceptor()); // 添加客戶端in log攔截器  
        client.getOutInterceptors().add(new LoggingOutInterceptor()); // 添加客戶端out log攔截器  

        System.out.println(helloService.sayHello("zhangsan"));  
    }  
}  </pre><a style="text-indent:0px;" title="派生到我的代碼片" href="/misc/goto?guid=4959555633058627956" target="_blank"></a></div>

</div> </div>

其他程序代碼請參考上一篇博客: http://blog.csdn.net/zdp072/article/details/27829831

客戶端需要引入以下jar包: cxf-2.2.10.jar  wsdl4j-1.6.2.jar  XmlSchema-1.4.5.jar


3. 日志如下:

- - 服務端

    2014-6-7 23:04:28 org.apache.cxf.service.factory.ReflectionServiceFactoryBean buildServiceFromClass  
    信息: Creating Service {http://impl.service.zdp.com/}HelloServiceImplService from class com.zdp.service.HelloService  
    2014-6-7 23:04:28 org.apache.cxf.endpoint.ServerImpl initDestination  
    信息: Setting the server's publish address to be http://localhost:80/sayHello  
    2014-06-07 23:04:28.718::INFO:  Logging to STDERR via org.mortbay.log.StdErrLog  
    2014-06-07 23:04:28.726::INFO:  jetty-6.1.21  
    2014-06-07 23:04:28.799::INFO:  Started SelectChannelConnector@localhost:80  
    Web Service 暴露成功  
</div> </div>

    • 客戶端

          2014-6-7 23:05:26 org.apache.cxf.service.factory.ReflectionServiceFactoryBean buildServiceFromWSDL
      信息: Creating Service {http://impl.service.zdp.com/}HelloServiceImplService from WSDL: http://localhost/sayHello?wsdl
      2014-6-7 23:05:26 org.apache.cxf.interceptor.LoggingOutInterceptor$LoggingCallback onClose

      信息: Outbound Message

      ID: 1
      Address: http://localhost/sayHello
      Encoding: UTF-8
      Content-Type: text/xml
      Headers: {SOAPAction=[""], Accept=[/]}

      Payload: <soap:Envelope xmlns:soap=" xmlns:ns2=";

      2014-6-7 23:05:26 org.apache.cxf.interceptor.LoggingInInterceptor logging

      信息: Inbound Message

      ID: 1
      Response-Code: 200
      Encoding: UTF-8
      Content-Type: text/xml; charset=utf-8
      Headers: {content-type=[text/xml; charset=utf-8], Content-Length=[275], Server=[Jetty(6.1.21)]}

      Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org /soap/envelope /"><soap:Body><ns1:sayHelloResponse xmlns:ns1="http: //service.zdp.com/"><return>zhangsan, 您好! 現在的時間 是: Sat Jun 07 23:05:26 CST 2014</return></ns1:sayHelloResponse></soap:Body></soap:Envelope>

      zhangsan, 您好! 現在的時間是: Sat Jun 07 23:05:26 CST 2014 </pre></div> </div> </div>

      三. CXF自定義攔截器

      如何使用CXF進行權限控制呢?

      思路: 服務器端要求input消息總是攜帶有用戶名, 密碼信息, 如果沒有用戶名和密碼信息, 直接拒絕調用.\

      代碼實現:

      1. 服務器端攔截器:

          /**

      • 服務端權限攔截器 */
        public class AuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

        public AuthInterceptor() {

         super(Phase.PRE_INVOKE); //攔截器在調用方法之前攔截SOAP消息  
        

        }

        // 攔截器操作
        @Override
        public void handleMessage(SoapMessage msg) throws Fault {

         System.out.println("come to auth interceptor...");  
         //獲取SOAP消息的所有Header  
         List<Header> headers = msg.getHeaders();  
        
         if(headers == null || headers.size() < 1) {  
             throw new Fault(new IllegalArgumentException("沒有Header,攔截器實施攔截"));  
         }  
         //獲取Header攜帶是用戶和密碼信息  
         Header firstHeader = headers.get(0);  
         Element element = (Element) firstHeader.getObject();  
        
         NodeList userNameElement = element.getElementsByTagName("userName");  
         NodeList passwordElement = element.getElementsByTagName("password");  
        
         if (userNameElement.getLength() != 1) {  
             throw new Fault(new IllegalArgumentException("用戶名格式不對"));  
         }  
        
         if (passwordElement.getLength() != 1) {  
             throw new Fault(new IllegalArgumentException("用戶密碼格式不對"));  
         }  
        
         //獲取元素的文本內容  
         String userName = userNameElement.item(0).getTextContent();  
         String password = passwordElement.item(0).getTextContent();  
        
         // 實際項目中, 應該去查詢數據庫, 該用戶名,密碼是否被授權調用該webservice  
         if (!userName.equals("zhangsan") || !password.equals("123456")) {  
             throw new Fault(new IllegalArgumentException("用戶名或密碼不正確"));  
         }  
        

        }
        } </pre></div> </div> </div>

        2. 客戶端攔截器

            /**

      • 客戶端攔截器(在xml片段中加頭部) */
        public class AddHeaderInterceptor extends AbstractPhaseInterceptor<SoapMessage>{

        private String userName;
        private String password;

        public AddHeaderInterceptor(String userName, String password) {

         super(Phase.PREPARE_SEND);  
         this.userName = userName;  
         this.password = password;   
        

        }

        @Override
        public void handleMessage(SoapMessage msg) throws Fault {

         List<Header> headers = msg.getHeaders();  
        
         //創建Document對象  
         Document document = DOMUtils.createDocument();  
         Element element = document.createElement("authHeader");   
        
         //配置服務器端Head信息的用戶密碼  
         Element userNameElement= document.createElement("userName");   
         userNameElement.setTextContent(userName);  
         Element passwordElement = document.createElement("password");   
         passwordElement.setTextContent(password);  
        
         element.appendChild(userNameElement);  
         element.appendChild(passwordElement);  
         headers.add(new Header(new QName(""), element));  
         /** 
          * 生成的XML文檔 
          * <authHeader> 
          *      <userName>zhangsan</userName> 
          *      <password>123456</password> 
          * </authHeader> 
          */  
        

        }
        } </pre></div> </div> </div>

  • 服務端</span>

        public class MyServer {

     public static void main(String[] args) {  
         HelloService helloService = new HelloServiceImpl();  
         EndpointImpl epi = (EndpointImpl)Endpoint.publish("http://localhost/sayHello", helloService);  
    
         // 添加服務器端in 權限攔截器, 該AuthInterceptor就會負責檢查用戶名, 密碼是否正確  
         epi.getInInterceptors().add(new AuthInterceptor());   
         System.out.println("Web Service 暴露成功");  
     }  
    

    } </pre></div> </div> </div>

  • 客戶端</span>

    public class MyClient {
    public static void main(String[] args) {

     HelloServiceImplService factory = new HelloServiceImplService();  
    
     // 此處返回的只是webservice的代理  
     HelloService helloService = factory.getHelloServiceImplPort();  
     Client client = ClientProxy.getClient(helloService);  
     client.getOutInterceptors().add(new AddHeaderInterceptor("zhangsan", "123456"));   
     System.out.println(helloService.sayHello("zhangsan"));  
    

    }
    } </pre></div> </div> </div> 來自:http://blog.csdn.net/zdp072/article/details/29245575

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!