WebService Framework CXF Combat One Custom Interceptor (v)

Source: Internet
Author: User
Tags tagname

CXF has built-in interceptors, most of which are added by default to the Interceptor chain, and some interceptors can be added manually, such as manually adding CXF-provided log interceptors. You can also customize the interceptor, it is easy to implement a custom interceptor in CXF, Just inherit the subclass of Abstractphaseinterceptor or abstractphaseinterceptor (such as Abstractsoapinterceptor).

Custom Permission authentication blocker

The authorization authentication interceptor handles the authentication information in the SoapHeader, the client adds the authentication information in the SoapHeader when the request is initiated, the service side verifies the authentication information after receiving the request, verifies that the pass continues, and the checksum fails to return the error.

<!-- 认证信息格式如下 --><auth xmlns="http://www.tmp.com/auth">      <name>admin</name>      <password>admin</password>  </auth>
Client Add authorization Blocker
ImportJava.util.List;ImportJavax.xml.namespace.QName;ImportOrg.apache.cxf.binding.soap.SoapMessage;ImportOrg.apache.cxf.headers.Header;ImportOrg.apache.cxf.helpers.DOMUtils;ImportOrg.apache.cxf.interceptor.Fault;ImportOrg.apache.cxf.phase.AbstractPhaseInterceptor;ImportOrg.apache.cxf.phase.Phase;ImportOrg.w3c.dom.Document;ImportOrg.w3c.dom.Element;/** * Add authorization Blocker * to add authorization when a client sends a request * @author [email protected] * */ Public  class authaddinterceptor extends abstractphaseinterceptor<  SoapMessage> {     Public Authaddinterceptor(){//Prepare to send phase        Super(Phase.prepare_send); }@Override     Public void Handlemessage(SoapMessage message)throwsFault {list//element auth = doc.createelement ("auth");Element auth = Doc.createelementns ("Http://www.tmp.com/auth","Auth"); Element name = Doc.createelement ("Name"); Name.settextcontent ("Admin"); Element Password = doc.createelement ("Password"); Password.settextcontent ("Admin");          Auth.appendchild (name);        Auth.appendchild (password); Headers.add (NewHeader (NewQName (""), auth)); }}
Server-Side authorization authentication blocker
ImportJava.util.List;ImportJavax.xml.namespace.QName;ImportOrg.apache.cxf.binding.soap.SoapMessage;ImportOrg.apache.cxf.headers.Header;ImportOrg.apache.cxf.interceptor.Fault;ImportOrg.apache.cxf.phase.AbstractPhaseInterceptor;ImportOrg.apache.cxf.phase.Phase;ImportOrg.w3c.dom.Element;ImportOrg.w3c.dom.NodeList;/** * Server Input Interceptor * Interception Request no authorization information * @author [email protected] * */ Public  class authvalidateinterceptor extends abstractphaseinterceptor<  SoapMessage> {     Public Authvalidateinterceptor(){Super(Phase.pre_invoke); }@Override     Public void Handlemessage(SoapMessage message)throwsFault {listif(Headers = =NULL|| Headers.size () <1) {Throw NewFault (NewException ("no license information!" ")); } Element auth =NULL;//Get authorization information element         for(Header header:headers)            {QName QName = Header.getname ();            String ns = Qname.getnamespaceuri (); String tagName = Qname.getlocalpart ();if(ns! =NULL&& Ns.equals ("Http://www.tmp.com/auth") && TagName! =NULL&& Tagname.equals ("Auth") {auth = (Element) header.getobject (); Break; }        }//If the authorization information element does not exist, the prompt is incorrect        if(Auth = =NULL){Throw NewFault (NewException ("no license information!" ")); } NodeList NameList = Auth.getelementsbytagname ("Name"); NodeList pwdlist = Auth.getelementsbytagname ("Password");if(Namelist.getlength ()! =1|| Pwdlist.getlength ()! =1){Throw NewFault (NewException ("The authorization information is wrong!" ")); } String name = Namelist.item (0). Gettextcontent (); String Password = Pwdlist.item (0). Gettextcontent ();if(!"Admin". Equals (name) | | !"Admin". Equals (password)) {Throw NewFault (NewException ("The authorization information is wrong!" ")); }    }}
Server-Side Interceptor configuration
<?xml version= "1.0" encoding= "UTF-8"?><beans  xmlns  =< Span class= "Hljs-value" > "Http://www.springframework.org/schema/beans"  xmlns:    XSI  = "http://www.w3.org/2001/XMLSchema-instance"  xmlns:jaxws  = "Http://cxf.apache.org/jaxws"  Span class= "Hljs-attribute" >xmlns:soap  = "Http://cxf.apache.org/bindings/soap"  xsi:schemalocation  = "Http://www.springframe Work.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/ Bindings/soap http://cxf.apache.org/schemas/configuration/soap.xsd Http://cxf.apache.org/jaxws Http://cxf.apache. Org/schemas/jaxws.xsd ";     <jaxws:endpoint id="Hellowsendpoint" implementor="#helloWS" Address="/hello">        <jaxws:ininterceptors>            <Bean class="Org.apache.cxf.interceptor.LoggingInInterceptor"> </Bean>            <Bean class="Com.rvho.cxfserver.interceptor.AuthValidateInterceptor" ></Bean>        </jaxws:ininterceptors>        <jaxws:outinterceptors>            <Bean class="Org.apache.cxf.interceptor.LoggingOutInterceptor"></Bean>        </jaxws:outinterceptors>    </jaxws:endpoint></Beans>
Client request
new JaxWsProxyFactoryBean();factory.setServiceClass(HelloWS.class);factory.setAddress("http://localhost:8280/cxfserver/services/hello");factory.getInInterceptors().add(new org.apache.cxf.interceptor.LoggingInInterceptor());//客户端授权拦截器factory.getOutInterceptors().add(new com.rvho.cxfclient.interceptor.AuthAddInterceptor());factory.getOutInterceptors().add(new org.apache.cxf.interceptor.LoggingOutInterceptor());HelloWS helloWS = factory.create(HelloWS.class);String welcome = helloWS.welcome("[email protected]");
CXF log Blocker

CXF provides input log interceptors Loggingininterceptor and output log interceptors Loggingoutinterceptor, which can be used on the server as well as on the client side. When testing or debugging, the log interceptor can be used to output the server, client requests and received information.

Service-Side Log content
July 30, 2015 10:51:37 am Org.apache.cxf.services.HelloWSService.HelloWSPort.HelloWSinformation: Inbound message----------------------------Id:1address:http://localhost:8280/cxfserver/services/helloencoding:utf-8http-method:postcontent-type:text/xml; Charset=utf-8headers: {accept=[*/*], Cache-control=[no-cache], connection=[keep-alive], content-length=[212], content-type=[text/xml; Charset=UTF-8], HOST=[LOCALHOST:8280], Pragma=[no-cache], soapaction=[""], User-agent=[apache CXF 3.1.1]}Payload: <soap:envelope xmlns:soap= "http://schemas.xmlsoap.org/soap/envelope/" ><soap:Body>< Ns2:welcome xmlns:ns2= "Http://www.tmp.com/services/hello" ><name>[email protected]</name></ns2: Welcome></soap:body></soap:envelope>--------------------------------------July 30, 2015 10:51:37 am Org.apache.cxf.services.HelloWSService.HelloWSPort.HelloWSinformation: Outbound message---------------------------Id:1response-code:200encoding:utf-8content-type:text/xmlheaders: {}Payload: <soap:envelope xmlns:soap= "http://schemas.xmlsoap.org/soap/envelope/" ><soap:Body>< Ns2:welcomeresponse xmlns:ns2= "Http://www.tmp.com/services/hello" ><return> Welcome to use cxf! [Email protected]</return></ns2:welcomeresponse></soap:body></soap:envelope>----------- ---------------------------
Client log Content
July 30, 2015 10:51:37 am Org.apache.cxf.services.HelloWSService.HelloWSPort.HelloWSinformation: Outbound message---------------------------id:1address:http://localhost:8280/cxfserver/services/helloencoding:utf-8http-method:postcontent-type:text/ Xmlheaders: {accept=[*/*], soapaction=[""]}Payload: <soap:envelope xmlns:soap= "http://schemas.xmlsoap.org/soap/envelope/" ><soap:Body>< Ns2:welcome xmlns:ns2= "Http://www.tmp.com/services/hello" ><name>[email protected]</name></ns2: Welcome></soap:body></soap:envelope>--------------------------------------July 30, 2015 10:51:37 am Org.apache.cxf.services.HelloWSService.HelloWSPort.HelloWSinformation: Inbound message----------------------------Id:1response-code:200encoding:utf-8content-type:text/xml;charset=utf-8headers: {content-type=[text/xml;charset= UTF-8], Date=[thu, Jul 02:51:37 GMT], server=[apache-coyote/1.1], transfer-encoding=[chunked]}Payload: <soap:envelope xmlns:soap= "http://schemas.xmlsoap.org/soap/envelope/" ><soap:Body>< Ns2:welcomeresponse xmlns:ns2= "Http://www.tmp.com/services/hello" ><return> Welcome to use cxf! [Email protected]</return></ns2:welcomeresponse></soap:body></soap:envelope>----------- ---------------------------Welcome to use cxf! [Email protected]

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

WebService Framework CXF Combat One Custom Interceptor (v)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.