This article is the thirteent from the J2EE Web Service Development Series. This article will first briefly introduce Web service security related technologies and development tools, then introduce the method of signing and verifying using the WSSecurity tool SOAP message; next discussion The ready-made WS-Security tool, combined with the Handler model to develop an AXIS to implement the General Application Framework for WS-Security.
You need the following knowledge and tools before reading this article:
Apache axis1.1, will be used initially; Tomcat 5.0.16 or more, will be preliminary; SOAP Message programming knowledge; Java security programming basic knowledge; JAX-RPC programming basic knowledge; servlet development experience; Sun Provide JAX-RPC reference implementation (JAXRPC-IMPL.jar, can be found in J2EESDK1.4 or JWSDP1.4); a JSSE security provider (such as ISNetworks); Trust Services Integration Kit, available at http://www.xmltrustCenter Get it on .org.
The reference materials of this article are found.
All code in this article is downloaded here.
Web Services Security Related Technology and Development Tools Web Service Security Specification is a set of mechanisms that help web service developers guarantee SOAP messaging. WS-Security specifically describes the enhancement of existing SOAP messaging, which provides protection levels for application message integrity, message confidentiality, and single message authentication for SOAP messages. These basic mechanisms can be combined in a variety of ways to suit a variety of security models that use multiple encryption techniques.
Focusing on Web services, there are many related technologies, such as WS-Security, WS-TRACE, etc., in addition, there are the following related art:
XML Digital Signature (XML Digital Signature) XML Encryption (XML Encryption) XKMS (XML Key Management Specification) XACML (eXtensible Access Control Markup Language) SAML (Secure Assertion Markup Language) ebXML Message Service Security Identity Management & Liberty Project
Since this article is an exemplary article, there is no detailed discussion for WS-Security, you can find many related information (see Resources) in the DEVELPERWORKS Web service security.
Trust Services Integration KIT provides a WS-Security implementation. You can get the database file from http://www.xmltrustcenter.org, which is WSSecurity.jar and Tsik.jar, respectively. WSSecurity.jar contains a WSSecurity class, which can be used to digital sign and verify, encrypt and decrypt XML.
Below we use WS-Security to digitally sign the SOAP message and then verify.
Signation and verification of SOAP messages
Use WSSecurity to sign the SOAP message digital signature before signing the SOAP message, first become a keystore. KeyStore contains identity information required for digital signatures. Create keystore by batch scripts:
Routine 1 Create KeyStore (Server.KeyStore)
Set server_dn = "cn = hellking-server, ou = Huayuan, O = Huayuan, L = beijingc, s = beijing, c = cn" set ks_pass = -storepass changeit
Set Ks_Type = -storeType Jks
Set keyinfo = -keyalg rsa
# Generate the server keystore.
KeyTool -Genkey-DName% Server_DN%% KS_Pass%% KS_TYPE% -KeyStore
Server.KeyStore% Keyinfo% -Keypass Changeit
The SignandVerifySoAP class contains a method of signing XML, which is Sign (), which signs the SOAP message, then outputs the WS-Security-compatible SOAP message. Let's see the specific code.
Routines 2 Signature SOAP Message
Package com.hellking.study.webservice;
Import com.verisign.messaging.wssecurity;
...
Public class sign signalverifysoap {
Final String Key_Store = "Server.KeyStore";
Final string Sote_pass = "changeit";
Final String Key_Alias = "mykey";
Final String Target_file = "SIGNED.XML"; // Signed SOAP Message
Final String Soure_File = "Source.xml"; // Signature Soap Message
Final string key_type = "jks";
/ **
* Signature XML
* /
Public void sign ()
{
Try
{
System.out.println ("Start Signature Soap Messages, Use the Key Library:" Key_Store "/ N");
// Get private key and related certificates, please refer to Java Security Programming Related Books
FileInputStream FileInputStream = New FileInputStream (Key_Store);
System.out.println (java.security.keystore.getDefaultType ());
Java.security.keystore store = java.security.keystore.getInstance (key_type);
Store.load (fileInputstream, Sote_pass.tochararray ());
PrivateKey Key = (PrivateKey) Store.getKey (key_alias, sot_pass.tochararray ());
X509Certificate Certification = (x509certificate) Store.getCertificate (Key_Alias);
// read the XML source file to the document
Document Source = Readfile (Soure_File);
SigningKey SigningKey = SigningKeyFactory.makesIgningKey (key);
KeyInfo Keyinfo = New Keyinfo ();
Keyinfo.setcertificate; wssecurity wssecurity = new wssecurity ();
WSSecurity.SetPreferRednamespace ("http://schemas.xmlsoap.org/ws/2003/06/secext");
/ / Sign for SOAP messages
WSSecurity.sign (Source, SigningKey, KeyInfo);
/ / Save the Signed SOAP message
Writefile (Source, New FileoutPutStream) and the Target_File);
System.out.println ("Write the files after the signature:" Target_File ", please see the result!");
}
Catch (Exception E)
{
E.PrintStackTrace ();
}
}
Before performing this procedure, set wssecurity.jar, source.xml, and tsik.jar into the classpath environment variable. SOAP before signing is:
SOAP message before the routine 3 signature (Source.xml)
XML Version = "1.0" encoding = "UTF-8"?>
XMLns: sopenv = "http://schemas.xmlsoap.org/soap/envelope/" XMLns: xsd = "http://www.w3.org/2001/xmlschema" XMLns: xsi = "http://www.w3.org/2001/xmlschema-instance"> XMLns: ns1 = "http://hellking.webservices.com/"> ns1: getTax> soapenv: body> soapenv: envelope> Signed SOAP messages shown in routine 4. SOAP message after the routine 4 signature (Signed.xml) XML Version = "1.0" encoding = "UTF-8"?> XMLns: XSD = "http://www.w3.org/2001/xmlschema" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance"> ValueType = "wsse: X509v3" wsu: Id = "wsse-ee805a80-cd95-11d8-9cf9-fd6213c0f8be" xmlns: wsu = "http://schemas.xmlsoap.org/ws/2003/06/utility"> MIICUjCCAbsCBEDB0GIwDQYJKoZIhvcNAQE ... Vktkpw == wsse: binarysecurityToken> ds: transforms> ds: transforms> ds: reason> ds: signedinfo> / wtilfrjt3zava6k3nhgcyj6tn / 9kzwwxh1rkftftx9xdq6xn p6m YBM1YEECTWKJD7XCXDYDENS2KYOHONX1U = ds: signaturevalue> ds: keyinfo> ds: signature> wsse: security> wsu: TimeStamp> soapenv: header> ns1: getTax> soapenv: body> soapenv: envelope> In the SOAP message after the signature, the header contains the signature information and the key required to verify the SOAP message. Verify the SOAP message to verify the SOAP message is to generate a Trustverifier object using the information of KeyStore, then call the WSSecurity's Verify method to verify. Routine 5 verify the SOAP message after the signature / ** * Verify SOAP messages that have been signed * / Public void verify () { Try { System.out.println ("Start Test SOAP Message, Use the Key Library:" Key_Store "/ N"); // Get private key and related certificates, please refer to Java Security Programming Related Books FileInputStream FileInputStream = New FileInputStream (Key_Store); Java.security.keystore store = java.security.keystore.getInstance (key_type); Store.load (fileInputstream, Sote_pass.tochararray ()); // Read the XML source file to document Document Source = ReadFile (Target_File); ORG.XMLTRUSTCENTER.VERIFIER.TRUSTVERIFIER VERIFIER = New org.xmltrustCenter.verifier.x509trustverifier (store); WSSecurity WSSecurity = new wssecurity (); com.verisign.Messaging.MessageValidity [] ResA = WSSecurity.Verify (Source, Verifier, Null, NULL); System.out.println ("Quality:"); For (int Len = 0; len System.out.println ("Result [" "] =" (ResA [Len] .issAlid ()? "Verification Pass": "Verification is not passed")); } } Catch (Exception E) { E.PrintStackTrace (); } } Executing the verify method of Signandverifysoap, you can see the following results. Figure 1 Verify SOAP message The application development framework to be developed in AXIS is based on the Handler implementation, which will reach the following objectives: This framework implements the WS-Security application based on the JAX-RPC environment, which can be deployed to anyws-security. In the Web service application in the AXIS environment, the specific application does not make any coding modifications. Because this is based on Handler implementation, we need to review some of the basic knowledge of Handler. SOAP Message Handler can access SOAP messages that represent RPC requests or responses. In JAX-RPC technology, the SOAP message Handler can be deployed on the server or can be used on the client. SOAP Message Handler is very similar to the Filter in Servlet technology. Their common feature is that the Handler / Filter can intercept these requests before sending to the target, and do some processes to achieve some auxiliary functions. Multiple Handler can form a Handler chain, and each handler on the chain completes a particular task. For example, some Handler perform permission verification, some Handler perform log processing, etc. For more detailed introduction of Handler, refer to this series of articles "J2EE Web Service Development Series: Use Handler to enhance the functionality of Web services". Realization Schemration Figure 2 is a specific schematic of this example. Figure 2 Handler combines WSSecurity to achieve WEB service security work principle The processing flow is as follows: 1. Client (WSSCLIENT) issues a calling web service request; 2. Client Handler (WSSecurityClientHandler intercepts the requested SOAP message; 3. Client handler performs digital signatures for intercepted SOAP messages (using client.keystore as a signature basis); 4. Client Handler encrypts the SOAP message after the signature (encrypted using RSA algorithm); 5. The encrypted SOAP message is transmitted to the target web service port via the Internet; 6. Server-side Handler (WSSecurityServerHandler intercepts the encrypted SOAP message; 7, the server-side Handler decrypts the encrypted SOAP message; 8. Server-side Handler authenticate to the SOAP message (Server.trustStore contains the trusted identity information), if the verification is not passed, will throw an exception; 9. Server-side Handler deletes elements related to WS-Security in Decrypted SOAP messages; 10. The original SOAP message after the decryption is sent to the target web service port (such as taxservice); 11. The target web service processes the web service request and then returns the response SOAP message; 12. Server-side Handler interceptive SOAP messages; 13. Server-side Handler performs digital signatures for intercepted SOAP messages (using server.keystore as a signature basis); 14. Server-side Handler encrypts the SOAP message after the signature (encrypted using RSA algorithm); 15. The encrypted SOAP message is transmitted to the destination client via the Internet; 16. Client Handler intercepts the encrypted SOAP message; 17. Client Handler decrypts the encrypted SOAP message; 18. Client handler authenticate to the SOAP message (Client.trustStore contains the trusted identity information), if the verification is not passed, will throw an exception; 19. Client Handler deletes elements related to WS-Security in Decrypted SOAP messages; 20. The decrypted SOAP message is sent to the target client, and the client output call results. As can be seen from the above, in a SOAP call round, the SOAP message is processed four times. Basically, the process of "signature 'encryption' decryption 'verification". Creating a related key library client and server have related key libraries, where: Client.KeyStore: The identity information of the client itself; client.trustStore: The identity information of the client trust, in this case, the server's identity information is included; Server.KeyStore: The server itself; server.trustStore: The identity information trusted by the server (ie client identity information). You can create the above four key libraries using the following batch scripts. Routine 6 Create a related key library (Gen-Cer-Store.bat) Set server_dn = "cn = hellking-server, ou = Huayuan, o = Huayuan, L = beijingc, s = beijing, c = cn" Set client_dn = "cn = hellking-client, ou = tsinghua, o = tsinghua, l = beijing, s = beijing, c = cn" Set ks_pass = -storepass changeit Set keyinfo = -keyalg rsa # Generate server.KeyStore. KeyTool -Genkey -Dname% server_dn%% KS_Pass%-KeyStore Server.KeyStore% KeyInfo% -KeyPass Changeit # Export a digital certificate from Server.KeyStore. Keytool -Export -File Test_axis.cer% KS_Pass%-Keystore Server.KeyStore # From the server's digital certificate to the TrustStore to the client trust. Keytool-Import -File Test_axis.cer% KS_Pass%-KeyStore Client.trustStore -Alaias ServerKey -NoPrompt # Generate Client.KeyStore. KeyTool -Genkey -Dname% Client_DN%% KS_Pass%-KeyStore Client.KeyStore% KeyInfo% -KeyPass Changeit # Export a digital certificate from Client.KeyStore. Keytool -Export -File Test_axis.cer% KS_Pass%-Keystore Client.KeyStore # From the client's digital certificate to the truststore of the server trusted. KeyTool-Import -File Test_axis.cer% KS_Pass%-KeyStore Server.trustStore -Alaias ClientKey -NoPrompt #end Signature, encryption, decryption, authentication implementation of SOAP messages, encrypted, decrypt, authentication, and authentication in a class named WSSHELPER. Routine 7 signature, encryption, decryption, authentication function implementation? D? Dwsshelper.java Package com.hellking.study.webservice; Import com.verisign.messaging.wssecurity; ... Public class wsshelper { Static string provider = "isnetworks"; // JSSE security provider. // Add a JSSE security provider, you can also use other security providers. Just support the DeSede algorithm. Static { Java.security.security.addprovider (new com.isnetworks.provider.jce.isnetworksprovider ()); } / ** * Digital signature for XML documents. * / Public Static Void Sign (Document Doc, String KeyStore, String StoreType, String storePass, string alias, string keypass "throws exception { FileInputStream FileInputStream = New FileInputStream (KeyStore); Java.security.keystore keystore = java.security.keystore.getInstance (StoreType); KeyStore.Load (fileInputstream, storepass.tochararray ()); PrivateKey Key = (PrivateKey) KeyStore.getKey (alias, keypass.tochararray ()); X509Certificate Cert = (x509certificate) KeyStore.getCertificate (alias); SigningKey SK = SigningKeyFactory.makesIgningKey (key); Keyinfo ki = new keyinfo (); Ki.setcertificate (CERT); WSSecurity WSSecurity = new wssecurity (); WSSecurity.sign (DOC, SK, KI); // Signature. } / ** * Authenticate the XML document. * / Public Static Boolean Verify (Document Doc, String KeyStore, String StoreType, String storepass) throws exception { FileInputStream FileInputStream = New FileInputStream (KeyStore); Java.security.keystore keystore = java.security.keystore.getInstance (StoreType); KeyStore.Load (fileInputstream, storepass.tochararray ()); Trustverifier Verifier = New X509Trustverifier (KeyStore); WSSecurity WSSecurity = new wssecurity (); Messagevalidity [] ResA = WSsecurity.verify (DOC, Verifier, Null, NULL); IF (resha.length> 0) Return ResA [0] .issalid (); Return False; } / ** * Encrypt the XML document. There must be a JSSE provider to encrypt. * / Public Static Void Encrypt (Document Doc, String KeyStore, String StoreType, String storepass, string alias) throws exception { Try { FileInputStream FileInputStream = New FileInputStream (KeyStore); Java.security.keystore keystore = java.security.keystore.getInstance (StoreType); KeyStore.Load (fileInputstream, storepass.tochararray ()); X509Certificate Cert = (x509certificate) KeyStore.getCertificate (alias); Publickey Pubk = CERT.GETPUBLICKEY (); KeyGenerator KeyGenerator = keygenerator.getInstance ("DeSede", Provider); KeyGenerator.init (168, New Securerandom ()); SecretKey Key = KeyGenerator.generateKey (); Keyinfo ki = new keyinfo (); Ki.setcertificate (CERT); WSSecurity WSSecurity = new wssecurity (); //encryption. Wssecurity.encrypt (DOC, Key, AlgorithmType.tripledes, Pubk, AlgorithmType.RSA1_5, KI); } Catch (Exception E) { E.PrintStackTrace (); } } / ** * Decrypt the document. * / Public Static Void Decrypt (Document Doc, String KeyStore, String StoreType, String storePass, string alias, string keypass "throwins Exception {fileInputstream fileinputstream = new fileinputstream (keystore); Java.security.keystore keystore = java.security.keystore.getInstance (StoreType); KeyStore.Load (fileInputstream, storepass.tochararray ()); PrivateKey Prvk2 = (PrivateKey) KeyStore.getKey (alias, keypass.tochararray ()); WSSecurity WSSecurity = new wssecurity (); // Decryption. WSSecurity.Decrypt (DOC, PRVK2, NULL); WSUTILS.RemovencryptedKey (DOC); // Remove EncryptedKey elements from WS-Security Header } Public Static Void RemoveWsseLements (Document Doc) THROWS Exception { WSUTILS.RemoveWSSELEments (DOC); / / Delete WSS-related elements. } } The ISNetWorks security provider is used in the WSSHELPER class, and ISNetworks implements RSA encryption and decryption algorithms. Of course, you can also use other security providers and can use different encryption algorithms. You can download the ISNetworks related package from the web. WSSHELPER includes a WSUTILS class, which deletes some WS-Security elements from the encrypted SOAP message, deleting SOAP messages after these elements can be processed by the final client or web server. Server-side Handler Development When the request arrives, the server handler calls the handleRequest method, performs the following procedure: Decrypt the Document "Authentication" Delete WSS Elements' to convert Document into SOAP messages. After the Web Services endpoint responds to the request, the handleresponse method will be called, perform the following procedure: Digital signature 'encryption' for the response SOAP message 'to convert the document into a SOAP message. Routine 8 server-side handler (WSSecurityServerHandler.java) Package com.hellking.study.webservice; ... // Server-side HANDLER Public Class WssecurityServerHandler Implements Handler { // Key library related information Private string keystorefile = NULL; Private string keystoreType = "jks"; . . . Public WSSecurityServerHandler () { System.out.println ("Server Handler: Constructor"); } / ** * Process request * Process: Decryption -> Authentication -> Delete WSS Elements' Convert Document to SOAP Messages. * / Public Boolean HandleRequest (MessageContext MessageContext) { System.out.println ("Start Process Request ..."); IF (MessageContext InstanceOf SOAPMESSAGECONTAXT) {TRY { SOAPMESSAGECONTEXT SOAPMESSAGECONTEXT = (SOAPMESSAGECONTEXT) MESSAGECONTEXT SOAPMESSAGE SOAPMESSAGE = SOAPMESSAGECONText.getMessage (); SOAPMESSAGE.WRITETO (System.out); Document Doc = MessageConveter.convertsoApMessageTodocument (SOAPMESSAGE); // Decryption WSSHELPER.DECRYPT (DOC, KeyStorefile, KeystoreType, KeyStorePassword, Keyalias, KeyEntrypassword; //Authentication WSSHELPER.VERIFY (DOC, TrustStorefile, TruststoreType, TrustStorePassword); / / Delete WSS elements WSSHELPER.Removewsselements (DOC); SOAPMESSAGE = MessageConveter.convertDocumenttosoApMessage (DOC); SOAPMESSAGECONTEXT.SETMESSAGE (SOAPMESSAGE); } catch (exception e) { System.err.Println ("An exception occurred during processing:" E); E.PrintStackTrace (); Return False; } } else { System.out.println ("MessageContext is an instance of the following classes:" messageContext.getClass ()); } System.out.Println ("Processing Request!"); Return True; } / ** * Processing response * Process: Digital Signature -> Encryption -> Convert Document into SOAP messages. * / Public Boolean Handleresponse (MessageContext MessageContext) { System.out.println ("Start processing Web Service Response ..."); IF (MessageContext InstanceOf SOAPMESSAGECONTEXT) { Try { SOAPMESSAGECONTEXT SOAPMESSAGECONTEXT = (SOAPMESSAGECONTEXT) MESSAGECONTEXT SOAPMESSAGE SOAPMESSAGE = SOAPMESSAGECONText.getMessage (); Document Doc = MessageConveter.convertsoApMessageTodocument (SOAPMESSAGE); WSSHELPER.SIGN (Doc, KeyStorefile, KeystoreType, KeyStorePassword, Keyalias, KeyEntrypassword; WSSHELPER.Encrypt (DOC, TrustStorefile, TruststoreType, TrustStorePassword, Certalias SOAPMESSAGE = MessageConveter.convertDocumenttosoApMessage (DOC); SOAPMESSAGECONTEXT.SETMESSAGE (SOAPMESSAGE); } catch (exception e) { System.err.Println ("The following error occurred while the response:" E); E.PrintStackTrace (); Return False; } } System.out.println ("Processing Response!"); Return True; } / ** * Initialization, mainly to initialize some related parameters. * / Public void init (HandlerInfo config) { System.out.println ("WSSecurity ServerHandler Initialization"); Object param = "" Map configs = config.getHandlerConfig (); KeyStorefile = (string) configs.get ("keystorefile"); TrustStorefile = (String) configs.get ("truststorefile"); ... // Other parameters initialization } ... } Client Handler Development Client Handler can be any JAX-RPC-compatible Handler processor. For example, the Axis Handler implementation or the JAX-RPC Handler reference implementation provided by Sun. Here, the latter is used as the client Handler processor. The client Handler is the same as the server-side Handler principle, but the process is completely opposite. Routine 9 Client Handler (WSSecurityClientHandler.java) Package com.hellking.study.webservice; ... // Client Handler Public Class WssecurityClientHandler Implements Handler { // Key library related information ... / ** * Process request * Process: Digital Signature -> Encryption -> Convert Document into SOAP messages. * / Public Boolean HandleRequest (MessageContext MessageContext) { System.out.println ("Start Process Request ..."); ... WSSHELPER.SIGN (Doc, KeyStorefile, KeystoreType, KeyStorePassword, Keyalias, KeyEntrypassword; WSSHELPER.Encrypt (DOC, TrustStorefile, TruststoreType, TrustStorePassword, Certalias SOAPMESSAGE = MessageConveter.convertDocumenttosoApMessage (DOC); SOAPMESSAGECONTEXT.SETMESSAGE (SOAPMESSAGE); ... System.out.Println ("Processing Request!"); Return True; } / ** * Processing response * Process: Decryption -> Authentication -> Delete WSS Elements' Convert Document to SOAP Messages. * / Public Boolean Handleresponse (MessageContext MessageContext) { System.out.println ("Start processing Web Service Response ..."); ... WSSHELPER.DECRYPT (DOC, KeyStorefile, KeystoreType, KeyStorePassword, Keyalias, KeyEntrypassword; WSSHELPER.VERIFY (DOC, TrustStorefile, TruststoreType, TrustStorePassword); WSSHELPER.RemoveWsSelements (DOC); SOAPMESSAGE = MessageConveter.convertDocumenttosoApMessage (DOC); System.out.println ("The Final Message IS:"; SOAPMESSAGE.WRITETO (System.out); SOAPMESSAGECONTEXT.SETMESSAGE (SOAPMESSAGE); ... System.out.println ("Processing Response!"); Return True; } / ** * Initialization, mainly to initialize some related parameters. * / Public void init (HandlerInfo config) { ... } ... } To deploy server-side Handler In order to use Handler, you need to specify this Handler in the Web Service Deployment Descriptor. The initialization parameter contained in the handler is also described, as shown in routine 10. Routine 10 Server-Directory Handler Deployment Code Value = "com.hellking.study.webservice.wssecurityserhandler" /> Value = "k: //jakarta-tomcat-5.0.16//server.keystore" /> Value = "k: //jakarta-tomcat-5.0.16//server.truststore" /> handler> requestflow> Value = "com.hellking.study.webservice.wssecurityserhandler" /> Value = "k: //jakarta-tomcat-5.0.16//server.keystore" /> Value = "k: //jakarta-tomcat-5.0.16//server.truststore" /> handler> responseflow> service> RequestFlow represents the request for Web Services PersonalTaxServicePort handles the Handler chain. There is only one handler here, it is WSSecurityServerHandler. When the Web service request reaches the PersonalTAXServicePort, the HandleRequest method of WSSecurityServerHandler will be automatically called. Note: When deploying, change the Handler related parameters to consistent with the target's web services, such as the path of TrustStorefile, etc. Call Test Here to call the web service in the way, first write a web service interface. Routines 11 TaxServiceInterface Package com.hellking.study.webservice; ... / ** * Personal income tax web service. * / Public Interface TaxServiceInterface Extends Remote { Public Double GetTax (Double Salry) throws java.rmi.remoteexception; } The WSSClient client program is to access Web services in a proxy way. Because of the use of Handler, WSSecurityClientHandler is registered through the registerhandlers () method before access, and the relevant parameters of WSSecurityClientHandler are initialized. Of course, the JAX-RPC "Reference Implement" also supports describing Handler information in the web service client configuration file, so you don't need to register with the Handler in the client code, you can refer to the relevant documentation. Routine 12 Test the client program (WSSCLIENT) Package com.hellking.study.webservice; ... / ** * WEB services that need to be verified * / Public Class WssClient { Static Final Double Salary = 5000; Public static void main (string [] args) { Try { // The server's URL needs to be changed according to the situation. String endpointurl = "http:// localhost: 8080 / axis / service / personaltaxserviceport"; String WSDLURL = EndPointURL "? WSDL"; Java.net.url targeturl = new java.net.URL (WSDLURL); String namespaceuri = "http://hellking.Webservices.com/"; String svcname = "personaltaxservice"; String portname = "PersonalTaxServicePort"; ServiceFactory svcfactory = servicefactory.newinstance (); Service svc = svcfactory.createservice (targeturl, new qname (namespaceuri, svcname)); // cfg represents the configuration information of the client. Java.util.hashmap cfg = new java.util.hashmap (); Cfg.PUT ("KeyStorefile", "Client.KeyStore"); Cfg.PUT ("TrustStorefile", "Client.trustStore); Cfg.PUT ("CERTALIAS", "Changeit"); Class hdlrclass = com.hellking.study.webservice.wssecurityclienthandler.class; Java.util.list List = svc.gethandlerRegistry (). GetHandlerchain (New Qname (Namespaceuri, PortName); List.add (new javax.xml.rpc.handler.HandlerInfo (HDLRClass, CFG, NULL); RegisterHandlers (SVC); TAXSERVICEINTERFACE MyProxy = (TAXSERVICEINTERFACE) SVC.GETPORT (New Qname (Namespaceuri, PortName), TAXSERVICEINTERFACE.CLASS); Double Ret = MyProxy.getTax (5000); System.out.Println ("Use the HTTP protocol to use the transfer protocol of the web service!"); System.out.println ("has been called successfully. Please refer to the output of the server!"); System.out.println ("Enter the wage" Salary ", pay personal income tax:" RET); } catch (exception e) { E.PrintStackTrace (); } } // Register Handler Private static void registerHandlers (Service Service) THROWS JAVAX.XML.RPC.ServiceException {java.util.hashmap cfg = new java.util.hashmap (); Cfg.PUT ("KeyStorefile", "Client.KeyStore"); Cfg.PUT ("TrustStorefile", "Client.trustStore); Cfg.PUT ("CERTALIAS", "Changeit"); / * * Package the client Handler to HandlerInfo and then add it to the Handler chain. * / Javax.xml.rpc.handler.handlerinfo info = new javax.xml.rpc.handler.handlerinfo (com.hellking.study.webservice.wssecurityclienthandler.class, cfg, null); Java.util.ArrayList HandlerList = New java.util.ArrayList (); HandlerList.Add (Info); / * * Get Handler Registration * / Javax.xml.rpc.handler.handlerRegistry HandlerRegistry = service.gethandlerRegistry (); / * * Add Handler to all ports. * / Java.util.iterator portiterator = service.getports (); While (portiterator.hasnext ()) { Object obj = portiterator.next (); Qname portname = (qname) OBJ; Handlerregistry.setHandlerchain (portname, handlerlist); } } } Note: Since the client uses the "JAX-RPC Reference Implementation" provided by Sun, you must set the jaxrpc-impl.jar package in the classpath environment variable, and do not set the Axis.jar to the client classpath environment variable, otherwise ClassCastException will appear. This is because AXIS is also an implementation of JAX-RPC, if it is in the ClassPath environment variable, when calling: When the ServiceFactory SvcFactory = ServiceFactory.newInstance () method, an AXIS's ServiceFactory implementation may be initialized. In this source code, the WSS-Client.bat file contains the WSSCLIENT script in the source code to modify some environment variable parameters to execute. Summary This article and the previous article introduces several different ways to implement Web service security, you can use different ways according to specific applications. For applications with high security levels, you can use basic authentication on the web server, use AXIS's Handler or use the servlet filter to implement access control; for the application of high security requirements, this article can be developed "Axis under Axis Implement the General Application Framework for WS-Security to achieve security. Reference