Java EE Web Services Development Series 13: Secure axis Web Services, part 2nd

Source: Internet
Author: User
Tags decrypt dname getmessage soap readfile sha1


Before reading this article you need the following knowledge and tools: Apache axis1.1, and will be used initially, Tomcat 5.0.16 above, and will be initially used, SOAP message (SOAP messages) programming knowledge, Java Security programming basics; JAX-RPC programming basics; The development experience of the servlet; the Jax-RPC reference implementation provided by Sun (Jaxrpc-impl.jar, found in j2eesdk1.4 or JWSDP1.4); A Jsse security provider (e.g. Isnetworks), trust Services integration Kit, can be obtained on http://www.xmltrustcenter.org.



See resources for the references in this article.



The entire code for this article is downloaded here.



WEB Services security-related technologies and development tools



The Web Services security specification is a set of mechanisms that can help Web service developers secure SOAP message exchange. Ws-security specifically describes the enhancements to existing SOAP messaging, providing a level of protection by applying message integrity, message confidentiality, and single message authentication to SOAP messages. These basic mechanisms can be combined in a variety of ways to accommodate multiple security models that use multiple cryptographic techniques.



Around the security of Web services, there are a number of related technologies, such as Ws-security,ws-trace, in addition, the following related technologies: 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 ) EbXML message Service security Identity Management & Liberty Project



Because this article is an example article, so do not do a detailed discussion of ws-security, you can find a lot of relevant information on the Develperworks Web Services Security topic (see Resources).



The Trust Services Integration Kit provides a ws-security implementation. You can obtain related library files from http://www.xmltrustcenter.org, respectively, Wssecurity.jar and Tsik.jar. The Wssecurity.jar contains a wssecurity class that you can use to digitally sign and authenticate XML, encrypt and decrypt it.



Here we use Ws-security to digitally sign the SOAP message and then verify it.





Back to the top of the page



Signature and validation of SOAP messages



Digitally sign a SOAP message by using wssecurity



Before the SOAP message is signed, a keystore is generated first. KeyStore contains the identity information required for digital signatures. Create KeyStore by using the following 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 server-side keystore.
keytool -genkey -dname% SERVER_DN%% KS_PASS%% KS_TYPE% -keystore
server.keystore% KEYINFO% -keypass changeit


                        


The Signandverifysoap class contains a method for signing XML, which is sign (), which will sign the SOAP message and then output and ws-security compatible SOAP messages. Here we look at the specific code.
routine 2 signature of SOAP messages


package com.hellking.study.webservice;
import com.verisign.messaging.WSSecurity;
...
public class SignAndVerifySoap {
     
    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"; // SOAP message before signing
    final String KEY_TYPE = "JKS";
     
    / **
     * Sign xml
     * /
    public void sign ()
    {
try
{
    System.out.println ("Start signing the SOAP message using the keystore:" + KEY_STORE + "\ n");
 
// Obtain the 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, SOTE_PASS.toCharArray ());
X509Certificate certification = (X509Certificate) store.getCertificate (KEY_ALIAS);
// read the XML source file into the document
Document source = readFile (SOURE_FILE);
SigningKey signingKey = SigningKeyFactory.makeSigningKey (key);
KeyInfo keyInfo = new KeyInfo ();
keyInfo.setCertificate (certification);
WSSecurity wsSecurity = new WSSecurity ();
wsSecurity.setPreferredNamespace ("http://schemas.xmlsoap.org/ws/2003/06/secext");
// Sign the SOAP message
wsSecurity.sign (source, signingKey, keyInfo);
// Save the signed SOAP message
writeFile (source, new FileOutputStream (TARGET_FILE));
System.out.println ("Write the signed file:" + TARGET_FILE + ", please see the result!");
    }
    catch (Exception e)
    {
e.printStackTrace ();
    }
    }


                        


Before executing this program, set the Wssecurity.jar, Source.xml, and Tsik.jar to the CLASSPATH environment variable. The soap before signing is:
SOAP Message (Source.xml) before the signature of routine 3


<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <soapenv:Body>
  <ns1:getTax soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:ns1="http://hellking.webservices.com/">
   <op1 xsi:type="xsd:double">5000.0</op1>
  </ns1:getTax>
 </soapenv:Body>
</soapenv:Envelope>


                        


The signed SOAP message is shown as routine 4.
SOAP Message (signed.xml) after the signature of routine 4


<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <soapenv:Header>
<wsse:Security xmlns:wsse="http://schemas.xmlsoap.org/ws/2003/06/secext">
<wsse:BinarySecurityToken EncodingType="wsse:Base64Binary"
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:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:SignedInfo>
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<ds:Reference URI="#wsse-ee5308f0-cd95-11d8-9cf9-fd6213c0f8be">
<ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<ds:DigestValue>ZjRVnI2g7kcX0h9r4JtiltpYQPA=</ds:DigestValue></ds:Reference>
<ds:Reference URI="#wsse-ee4e4e00-cd95-11d8-9cf9-fd6213c0f8be">
<ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<ds:DigestValue>moZ0d+8mH1kfNw0VEK39V0Td9EM=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>
fPpYrf0uNP8W2XVVIQNc3OQt2Wn90M/0uJ0dDZTNRR0NxBBBX36wSXt7NfI5Fmh4ru44Wk34EGI7mqMAE5O0
/wtIlFRJt3zAvA6k3nhgcYj6tn/9kZwwxh1RkFTfTX9xdQ6Xn+P6m+YBm1YEEcTWkJd7XcxdyDEns2kYOhONx1U=
</ds:SignatureValue>
<ds:KeyInfo><wsse:SecurityTokenReference>
<wsse:Reference URI="#wsse-ee805a80-cd95-11d8-9cf9-fd6213c0f8be"/>
</wsse:SecurityTokenReference>
</ds:KeyInfo>
</ds:Signature></wsse:Security>
<wsu:Timestamp xmlns:wsu="http://schemas.xmlsoap.org/ws/2003/06/utility">
<wsu:Created wsu:Id="
wsse-ee4e4e00-cd95-11d8-9cf9-fd6213c0f8be">2004-07-04T08:41:23Z</wsu:Created>
</wsu:Timestamp></soapenv:Header>
<soapenv:Body wsu:Id="wsse-ee5308f0-cd95-11d8-9cf9-fd6213c0f8be"
    xmlns:wsu="http://schemas.xmlsoap.org/ws/2003/06/utility">
  <ns1:getTax soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
    xmlns:ns1="http://hellking.webservices.com/">
   <op1 xsi:type="xsd:double">5000.0</op1>
  </ns1:getTax>
 </soapenv:Body>
</soapenv:Envelope>


                        


In a signed SOAP message, the header contains the signature information and the key required to validate the SOAP message. <SignedInfo> </SignedInfo> describes the content of signed messages. <signaturemethod algorithm= "Http://www.w3.org/2000/09/xmldsig#rsa-sha1"/> points out the signature algorithm (Signature method Algorithm). This algorithm is used to convert the output of the canonical algorithm to the signature value (Signature value). The Key Info element contains part of the digital certificate itself.



validating a signed SOAP message



Validating a SOAP message is using KeyStore information to generate the Trustverifier object and then invoking the Wssecurity verify method for validation.
routine 5 Verifying a signed SOAP message


/ **
     * Verify signed SOAP messages
     * /
    public void verify ()
    {
        try
        {
            System.out.println ("Begin checking SOAP messages, use keystore:" + KEY_STORE + "\ n");
         
        // Obtain the 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 into the 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 ("Test result:");
       for (int len = 0; len <resa.length; len ++) {
      System.out.println ("result [" + len + "] =" + (resa [len] .isValid ()? "Validation passed": "Validation failed"));
    }
    }
    catch (Exception e)
    {
        e.printStackTrace ();
    }
}


                        


To perform the Signandverifysoap verify method, you can see results similar to the following.
Figure 1 Validating a SOAP message





Back to the top of the page



The application framework of ws-security under axis



The application development framework to be developed is based on the handler implementation and will achieve the following goals: This framework is based on Ws-security applications in a JAX-RPC environment and can be deployed to any Web service application in an axis environment that needs to be implemented ws-security. At the same time the specific application does not make any coding modifications.



Since this is based on handler implementations, it is necessary to review some of the basics of handler.



SOAP messages handler have access to SOAP messages that represent RPC requests or responses. In Jax-RPC technology, SOAP message Handler can be deployed on the server or used on the client.



SOAP message Handler is very much like the filter in servlet technology, and their common feature is that before a request is sent to the target, Handler/filter can intercept the requests and do some processing on the request to achieve some auxiliary functions. Multiple handler can form a handler chain, and each handler on the chain completes a specific task. For example, some handler for permission verification, some handler for log processing and so on. For a more detailed description of handler, please refer to this series of Java EE Web Services Development Series VI: Using handler to enhance the functionality of Web services.



Implementation Principle



Figure 2 is a schematic diagram of the specific implementation of this example.
Figure 2 Handler The working principle of Web service security combined with wssecurity



The processing process is as follows:



1. The client (wssclient) makes a call to the Web service request;



2, the client handler (Wssecurityclienthandler) intercepts the requested SOAP message;



3. The client handler digitally sign the intercepted SOAP message (using Client.keystore as the basis of signature);



4, the client handler the signed SOAP message encryption (using the RSA algorithm encryption);



5. The encrypted SOAP message is transmitted over the Internet to the target Web service port;



6, server-side handler (Wssecurityserverhandler) interception of encrypted SOAP messages;



7, server-side handler to decrypt the encrypted SOAP message;



8, server-side handler to the SOAP message authentication (Server.truststore contains the trust of identity information), if the validation does not pass, will throw an exception;



9, server-side handler delete the decrypted SOAP message in the ws-security-related elements;



10. The original SOAP message after 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 a response SOAP message;



12, server-side handler interception of the response of the SOAP message;



13. Server-side handler digitally sign the captured SOAP message (using Server.keystore as the basis for signing);



14, server-side handler of the signed SOAP message encryption (using the RSA algorithm encryption);



15. Encrypted SOAP messages are sent over the Internet to the target client;



16, the client handler intercept the encrypted SOAP message;



17, the client handler the encrypted SOAP message to decrypt;



18. The client handler the SOAP message (Client.truststore contains the trusted identity) and throws an exception if the validation does not pass;



19, the client handler delete the decrypted SOAP message in the ws-security-related elements;



20. The decrypted SOAP message is sent to the target client, and the client outputs the result of the call.



As you can see from the above, SOAP messages are processed four times in a soap call round. are basically "signature" encryption ' decryption ' verification process.



create a related key library



Both the client and the server have the relevant KeyStore, in which: Client.keystore: The identity information of the client itself; Client.truststore: The identity information that the client trusts, in this case, the identity information is included; Server.keystore: Identity information for the server itself; Server.truststore: Identity information that the server trusts (that is, client identity information).



You can use the following batch script to create four key libraries above.
routine 6 Create a related KeyStore (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 digital certificate from server.keystore.
keytool -export -file test_axis.cer% KS_PASS% -keystore server.keystore
#Export the digital certificate from the server to the truststore trusted by the client.
keytool -import -file test_axis.cer% KS_PASS%
-keystore client.truststore -alias serverkey -noprompt
#Generate client.keystore.
keytool -genkey -dname% CLIENT_DN%% KS_PASS%
-keystore client.keystore% KEYINFO% -keypass changeit
#Export digital certificate from client.keystore.
keytool -export -file test_axis.cer% KS_PASS%
-keystore client.keystore
#Export the digital certificate from the client to a truststore trusted by the server.
keytool -import -file test_axis.cer% KS_PASS%
-keystore server.truststore -alias clientkey -noprompt
#end


                        


implementation of signature, encryption, decryption, authentication



The signature, encryption, decryption, and authentication of a SOAP message are placed in a class named Wsshelper.
implementation of routine 7 signature, encryption, decryption and authentication ――wsshelper.java


package com.hellking.study.webservice;
import com.verisign.messaging.WSSecurity;
...
public class WSSHelper {
Static String PROVIDER = "ISNetworks"; // JSSE security provider. Zh
// Add a JSSE security provider, you can also use other security providers. Just support the DESede algorithm.
Static static
...
java.security.Security.addProvider (
new com.isnetworks.provider.jce.ISNetworksProvider ());
}
/ **
Digitally sign 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 (
Aliaalias, 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 XML documents.
^ * * /
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 (resa.length> 0)
Return resa [0] .isValid ();
Return false;
}
/ **
Encrypt XML documents. You must have a JSSE provider to encrypt.
... * /
Public static void encrypt (Document doc, String keystore, String storetype,
String storepass, String alias) throws Exception {
To try
{{{
Zh
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.
SSecurity.encrypt (doc, key, AlgorithmType.TRIPLEDES,
(Pubk, AlgorithmType.RSA1_5, ki);
}
Ccatch (Exception e)
...
.E.printStackTrace ();
}
}
/ **
Decrypt the document.
^ * * /
Public static void decrypt (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 prvk2 = (PrivateKey) keyStore.getKey (
Aliaalias, keypass.toCharArray ());
WSSecurity wSSecurity = new WSSecurity ();
// Decrypt.
SecuritySSecurity.decrypt (doc, prvk2, null);
WsUtils.removeEncryptedKey (doc); // Remove the EncryptedKey element from the WS-Security Header
}
Public static void removeWSSElements (Document doc) throws Exception {
WsUtils.removeWSSElements (doc); // Remove WSS related elements.
}
}


                        


The Isnetworks security provider is used in the Wsshelper class, and the RSA encryption and decryption algorithm Isnetworks implemented. Of course, you can also use other security providers, and you can use different encryption algorithms. Isnetworks related packages can be downloaded from the network.



The wsshelper contains a wsutils class that removes some of the ws-security elements from the encrypted SOAP message before it can be processed by the end client or Web server.



server-side handler development



When the request arrives, the service-side handler calls the HandleRequest method, performing the following procedure: Decrypting the request SOAP message ' Authentication ' delete WSS element ' converts the document to a SOAP message. When a Web service endpoint responds to a request, it calls the Handleresponse method, performing the following procedure: Digitally sign the response's SOAP message to convert the document to a SOAP message.
routine 8 server-side handler (Wssecurityserverhandler.java)


package com.hellking.study.webservice;
...
// Server-side Handler
public class WSSecurityServerHandler implements Handler
{
        // Keystore related information
private String keyStoreFile = null;
        private String keyStoreType = "JKS";
        . . .
         
        public WSSecurityServerHandler ()
        {
            System.out.println ("Server Handler: Constructor");
        }
        / **
         * Processing requests
         * Process: Decrypt-> Authentication-> Delete WSS element 'Convert Document into SOAP message.
         * /
        public boolean handleRequest (MessageContext messageContext) {
         
                System.out.println ("Start processing request ...");
        if (messageContext instanceof SOAPMessageContext) {
            try {
    SOAPMessageContext soapMessageContext = (SOAPMessageContext) messageContext;
SOAPMessage soapMessage = soapMessageContext.getMessage ();
soapMessage.writeTo (System.out);
    Document doc = MessageConveter.convertSoapMessageToDocument (soapMessage);
                    // decrypt
WSSHelper.decrypt (doc, keyStoreFile, keyStoreType,
        keyStorePassword, keyAlias, keyEntryPassword);
                     //Authentication
WSSHelper.verify (doc, trustStoreFile, trustStoreType, trustStorePassword);
// Delete the WSS element
WSSHelper.removeWSSElements (doc);
soapMessage = MessageConveter.convertDocumentToSOAPMessage (doc);
soapMessageContext.setMessage (soapMessage);
            } catch (Exception e) {
System.err.println ("An exception occurred while processing the request:" + e);
e.printStackTrace ();
return false;
            }
        } else {
 System.out.println ("MessageContext is an instance of:" + messageContext.getClass ());
        }
         System.out.println ("Processing the request is complete!");
        return true;
    }
     
    / **
     * Processing response
     * Process: Digital Signature-> Encryption-> Convert Document to SOAP Message.
     * /
     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 processing the response:" + e);
e.printStackTrace ();
return false;
            }
        }
     
        System.out.println ("Processing response completed!");
        return true;
    }
    / **
     * Initialization is mainly to initialize some related parameters.
     * /
     public void init (HandlerInfo config) {
        System.out.println ("WSSecurityServerHandler initialization");
        Object param = "";
        Map configs = config.getHandlerConfig ();
        keyStoreFile = (String) configs.get ("keyStoreFile");
        trustStoreFile = (String) configs.get ("trustStoreFile");
        … // Other parameters initialization
    }
    ...
}


                        


Client Handler Development



The client handler can be any JAX-RPC compliant handler processor. such as the axis handler implementation or the Jax-RPC handler reference implementation provided by Sun. This uses the latter as the client handler processor.



The client handler is the same as the server-side handler principle, but the process is completely reversed.
Routine 9 Client handler (Wssecurityclienthandler.java)


package com.hellking.study.webservice;
...
// Client Handler
public class WSSecurityClientHandler implements Handler
{
       // Keystore related information
        ...
         
        / **
         * Processing requests
         * Process: Digital Signature-> Encryption-> Convert Document to SOAP Message.
         * /
        public boolean handleRequest (MessageContext messageContext) {
         
                System.out.println ("Start processing 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 the request is complete!");
        return true;
    }
     
    / **
     * Processing response
     * Process: Decrypt-> Authentication-> Delete WSS element 'Convert Document into SOAP message.
     * /
     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 completed!");
        return true;
    }
    / **
     * Initialization is mainly to initialize some related parameters.
     * /
     public void init (HandlerInfo config) {
        ...
    }
    ...
}


                        


Deploying server-side Handler



In order to use handler, you need to specify the use of this handler in the Web service deployment descriptor. The initialization parameters contained in handler are also described here, as shown in routine 10.
routine 10 server-side handler deployment code


<service name="PersonalTaxServicePort" provider="java:RPC">
<parameter name="allowedMethods" value="*"/>
<parameter name="className" value="com.hellking.study.webservice.PersonalTaxService"/>
<parameter name="wsdlTargetNamespace" value="http://hellking.webservices.com/"/>
<parameter name="wsdlServiceElement" value="PersonalTaxService"/>
<parameter name="wsdlServicePort" value="PersonalTaxServicePort"/>
<parameter name="wsdlPortType" value="PersonalTaxService"/>
<requestFlow>
 <handler type="java:org.apache.axis.handlers.JAXRPCHandler">
  <parameter name="scope" value="session"/>
  <parameter name="className"
          value="com.hellking.study.webservice.WSSecurityServerHandler"/>
  <parameter name="keyStoreFile"
          value="K:\\jakarta-tomcat-5.0.16\\server.keystore"/>
  <parameter name="trustStoreFile"
          value="K:\\jakarta-tomcat-5.0.16\\server.truststore"/>
  <parameter name="certAlias" value="clientkey"/>
 </handler>
</requestFlow>
<responseFlow>
 <handler type="java:org.apache.axis.handlers.JAXRPCHandler">
  <parameter name="scope" value="session"/>
  <parameter name="className"
          value="com.hellking.study.webservice.WSSecurityServerHandler"/>
  <parameter name="keyStoreFile"
          value="K:\\jakarta-tomcat-5.0.16\\server.keystore"/>
  <parameter name="trustStoreFile"
          value="K:\\jakarta-tomcat-5.0.16\\server.truststore"/>
  <parameter name="certAlias" value="clientkey"/>
 </handler>
</responseFlow>
</service>


                        


Requestflow represents a Personaltaxserviceport request processing handler chain for Web services. There is only one handler, Wssecurityserverhandler. When a Web service request arrives at Personaltaxserviceport, the Wssecurityserverhandler HandleRequest method is invoked automatically.



Note: When deploying, change the handler related parameters to match the target Web service, such as the Truststorefile path.



Call Test



The proxy is used here to invoke the Web service and write a Web service interface first.
routine Taxserviceinterface


package com.hellking.study.webservice;
...
/ **
  * Personal Income Tax Web Service.
  * /
public interface TaxServiceInterface extends Remote
{
     public double getTax (double salary) throws java.rmi.RemoteException;
}


                        


The Wssclient client program accesses a Web service through a proxy. Because of the use of handler, the Wssecurityclienthandler was registered by the Registerhandlers () method prior to access, and the related parameters of Wssecurityclienthandler were initialized. Of course, Jax-RPC "reference implementation" also supports the description of handler information in the Web service client configuration file, so that you do not need to register handler in client code, you can refer to the relevant documentation.
Routine 12 test client program (wssclient)


package com.hellking.study.webservice;
...
/ **
 * Invoke web services that require authentication
 * /
public class WSSClient
{
    static final double salary = 5000;
    public static void main (String [] args)
    {
        try {
            // The URL of the server needs to be changed according to the situation.
            String endpointURL = "http: // localhost: 8080 / axis / services / 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 as the transport protocol for Web services!");
            System.out.println ("Called successfully. See server output!");
            System.out.println ("input salary" + salary + "yuan, personal income tax payable:" + 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");
             
        / *
        * Encapsulate the client Handler into HandlerInfo and 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: Because the client uses the "Jax-RPC Reference implementation" provided by Sun, Therefore, you must set the Jaxrpc-impl.jar package in the CLASSPATH environment variable, and do not set the Axis.jar on the client CLASSPATH environment variables, otherwise there will be classcastexception exception. This is because axis is also a JAX-RPC implementation, if it is in the CLASSPATH environment variable, when the call:



Servicefactory svcfactory = Servicefactory.newinstance () method, it is possible to initialize an axis's servicefactory implementation.



This article source code in the client directory Wss-client.bat file contains the execution wssclient script, modified some environment variable parameters, to execute.





Back to the top of the page



Summarize



This article and the previous article introduced several different ways to implement Web services security, and you can use different approaches to the level of security requirements for specific applications. For applications with low security levels, you can use Basic authentication on a Web server, use axis handler, or use a servlet filter to access control; For applications with high security requirements, this article introduces the " The universal application framework for ws-security under axis to achieve security.





Back to the top of the page



Reference Java Security Programming

VeriSign Trust Services Integration Kit

Configure Tomcat 4 to use SSL

Sun jwsdp-1_1-tutorial

SOAP Security Extension: Digital signatures

SOAP-DSIG defines a data format that attaches an XML signature to a SOAP message

XML Encryption Workgroup

SOAP Header extensions: ws-security and Ws-license

A digital signature tutorial for SOAP messages

WEB Services Security Topics

Java EE Web Services Development Series VI: Using handler to enhance the functionality of Web services





Back to the top of the page



About the author



Chenyaqiang: Beijing Huayuan Tianyi Technology Co., Ltd. Senior software engineer, good at Java technology, has participated in a number of Java project design and development, Web services have a great interest and have a certain project experience. Love to learn, like new technology, has participated in the writing of many books. Good friends, you can contact him through cyqcims@mail.tsinghua.edu.cn.

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.