Webservice Archive

Two way SSL Webservice on Weblogic Server

This article provides sample Webservice and Webservice Client for two way SSL. It also demonstrates the use of WLSSSLAdapter class to send certificates to the server.

1. Create a JWS with the following policy  : Wssp1.2-2007-Https-ClientCertReq.xml

 

package examples.webservices.security_jws;

import weblogic.jws.WLHttpTransport;
import weblogic.jws.Policies;
import weblogic.jws.Policy;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.soap.SOAPBinding;

@WebService(name="SecureHelloWorldPortType", 
            serviceName="SecureHelloWorldService", 
            targetNamespace="http://www.bea.com")

@SOAPBinding(style=SOAPBinding.Style.DOCUMENT, 
             use=SOAPBinding.Use.LITERAL,
             parameterStyle=SOAPBinding.ParameterStyle.WRAPPED)

@WLHttpTransport(contextPath="SecureHelloWorldService", 
                 serviceUri="SecureHelloWorldService",
		 portName="SecureHelloWorldServicePort")

@Policy(uri = "policy:Wssp1.2-2007-Https-ClientCertReq.xml")

public class SecureHelloWorldImpl {

  @WebMethod()
  public String sayHello(String s) {
    return "Hello " + s;  
  }
}

2. Build and Deploy the service on WebLogic Server

3. Deploy a war file with the following jsp in another server.

<html>
<head>
<title>WS Client App</title>
</head>
<body bgcolor="#cccccc">
<blockquote>
<h2>Protected Page</h2>
</blockquote>

<%@ page import="examples.webservices.security_jws.client.SecureHelloWorldService"%>
<%@ page import="examples.webservices.security_jws.client.SecureHelloWorldService_Impl"%>
<%@ page import="examples.webservices.security_jws.client.SecureHelloWorldPortType"%>

<%@ page import="javax.xml.rpc.Stub"%>
<%@ page import="weblogic.wsee.connection.transport.https.WlsSSLAdapter"%>
<%@ page import="weblogic.security.SSL.TrustManager"%>
<%@ page import="java.security.cert.X509Certificate"%>

<%
 try
 {
    String wsdl = "https://localhost:7002/SecureHelloWorldService/SecureHelloWorldService?WSDL";
    //SecureHelloWorldService service = new SecureHelloWorldService_Impl(wsdl);
    SecureHelloWorldService service = new SecureHelloWorldService_Impl();
    SecureHelloWorldPortType port = service.getSecureHelloWorldServicePort();

    WlsSSLAdapter adapter = new WlsSSLAdapter();
    adapter.setKeystore("C://WSSecurity//LABS//twoway_jws//identity.jks","mystorepass".toCharArray(), "JKS" );
    adapter.setClientCert("mykey","mykeypass".toCharArray());
    adapter.setTrustManager( new TrustManager(){
                 public boolean certificateCallback(X509Certificate[] chain, int validateErr){
                   return true;
                 }
           }); 

   weblogic.wsee.connection.transport.https.HttpsTransportInfo info = new  weblogic.wsee.connection.transport.https.HttpsTransportInfo(adapter);
   Stub stub = (Stub)port;
   stub._setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY,"https://localhost:7002/SecureHelloWorldService/SecureHelloWorldService?WSDL");
   stub._setProperty("weblogic.wsee.client.ssladapter", adapter);

   out.println(port.sayHello("World"));
 } 
catch (Exception e)
{
out.println("File input error"+e);
}           

%>

</body>
</html>

4. Configure SSL on the server on which client app is deployed.

5. On the server on which the service is deployed , do the 2 way SSL configuration.

a) Go to Home >Summary of Servers > YourServer > SSL > Advanced >
Two Way Client Cert Behavior: Client Certs Requested and Enforced
Hostname Verification: None

b) Go to Home >Summary of Security Realms >myrealm >Providers >DefaultIdentityAsserter

Under Common

Chosen Select X509

Under Provider Specific

Trusted Client Principals: <CN of the client’s certificate>
Default User Name Mapper Attribute Type: CN
Use Default User Name Mapper: Checked

c) Create a user in the security realm with the CN value of the certificate.

6) Import the client’s public certificate in the trust store of the server.

Using RolesAllowed and SecurityRole annotations to secure Webservices on Weblogic

1. Write a JWS that uses the RolesAllowed and SecurityRole annotation

package examples.webservices.security_jws;

import weblogic.jws.WLHttpTransport;
import weblogic.jws.Policies;
import weblogic.jws.Policy;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.soap.SOAPBinding;

import weblogic.jws.security.RolesAllowed;
import weblogic.jws.security.SecurityRole;

@WebService(name="SecureHelloWorldPortType", 
            serviceName="SecureHelloWorldService", 
            targetNamespace="http://www.bea.com")

@SOAPBinding(style=SOAPBinding.Style.DOCUMENT, 
             use=SOAPBinding.Use.LITERAL,
             parameterStyle=SOAPBinding.ParameterStyle.WRAPPED)

@WLHttpTransport(contextPath="SecureHelloWorldService", 
                 serviceUri="SecureHelloWorldService",
		 portName="SecureHelloWorldServicePort")

@RolesAllowed (  { 
    @SecurityRole (role="testrole")
} ) 

public class SecureHelloWorldImpl {

  @WebMethod()
  public String sayHello(String s) {
    return "Hello " + s;  
  }
}

2) While deploying the EAR select custom roles

 

custom roles

3)

Go to myrealm> Realm Roles > Global Roles > Edit Globl Roles and create a new role
testrole and add an existing user to the role

custom roles

 

4) You can invoke the Webservice from SOAP UI by providing the username & password in the request properties.

 

SOAPUI

How to load webservices security policy from classpath

1) Add the following JAVA OPTION to the classpath

-Dweblogic.wsee.policy.LoadFromClassPathEnabled=true

2) Write a simple policy.

Encrypt.xml

 

<?xml version="1.0"?>
<wsp:Policy
  xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
  xmlns:wssp="http://www.bea.com/wls90/security/policy"
  >
  <wssp:Confidentiality>
    <wssp:KeyWrappingAlgorithm URI="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/>
    <wssp:Target>
      <wssp:EncryptionAlgorithm 
         URI="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"/>
      <wssp:MessageParts 
         Dialect="http://schemas.xmlsoap.org/2002/12/wsse#part">
         wsp:Body()
      </wssp:MessageParts>
    </wssp:Target>
    <wssp:KeyInfo/>
  </wssp:Confidentiality>
</wsp:Policy>

3) Write a JWS that uses this Policy

SecureHelloWorldImpl.java

 

package examples.webservices.security_jws;

import weblogic.jws.WLHttpTransport;
import weblogic.jws.Policies;
import weblogic.jws.Policy;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.soap.SOAPBinding;

@WebService(name="SecureHelloWorldPortType", 
            serviceName="SecureHelloWorldService", 
            targetNamespace="http://www.bea.com")

@SOAPBinding(style=SOAPBinding.Style.DOCUMENT, 
             use=SOAPBinding.Use.LITERAL,
             parameterStyle=SOAPBinding.ParameterStyle.WRAPPED)

@WLHttpTransport(contextPath="SecureHelloWorldService", 
                 serviceUri="SecureHelloWorldService",
		 portName="SecureHelloWorldServicePort")

@Policies({
    @Policy(uri="Encrypt.xml",direction=Policy.Direction.inbound)
	})

public class SecureHelloWorldImpl {

  @WebMethod()
  public String sayHello(String s) {
    return "Hello " + s;  
  }
}

4. Build the service.

5. By default policies are placed under the policy folder in WEB-INF

policy-folder

 

6. Create a jar having the policy file

WEB-INF\policies>jar -cvf policy.jar Encrypt.xml

7. Keep policy.jar in the classpath of the server. You can keep it at any location and add the jar to Weblogic Server classpath.
You can also keep it in your domain lib folder.

8. Remove the policies folder from the WEB-INF

9. Deploy the ear.

10. Check the WSDL. The policy should appear there.

wsdl

 

9. Access the application from any client.

10. Your SOAP Request should look like this.

 

<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
   <env:Header>
      <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" env:mustUnderstand="1">
         <ns1:EncryptedKey xmlns:ns1="http://www.w3.org/2001/04/xmlenc#" Id="hVJypuPV1a2vyBqJ">
            <ns1:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
            <ns2:KeyInfo xmlns:ns2="http://www.w3.org/2000/09/xmldsig#">
               <wsse:SecurityTokenReference xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="str_B42tel6VDu8at1J1">
                  <ns2:X509Data>
                     <ns2:X509IssuerSerial>
                        <ns2:X509IssuerName>CN=CertGenCAB,OU=FOR TESTING ONLY,O=MyOrganization,L=MyTown,ST=MyState,C=US</ns2:X509IssuerName>
                        <ns2:X509SerialNumber>94119899133620682327187254280110341585</ns2:X509SerialNumber>
                     </ns2:X509IssuerSerial>
                  </ns2:X509Data>
               </wsse:SecurityTokenReference>
            </ns2:KeyInfo>
            <ns1:CipherData>
               <ns1:CipherValue>SIa0pKmZU59OzQGjbYfk/+hbBoVvysjuWrOugwNelkSEW83ohLo/+QZGYqgnNgyo5xbqZp98sS5nPocf5pjuLA==</ns1:CipherValue>
            </ns1:CipherData>
            <ns1:ReferenceList>
               <ns1:DataReference URI="#BrYjknvNmVglOMV2" />
            </ns1:ReferenceList>
         </ns1:EncryptedKey>
      </wsse:Security>
   </env:Header>
   <env:Body>
      <ns1:EncryptedData xmlns:ns1="http://www.w3.org/2001/04/xmlenc#" Id="BrYjknvNmVglOMV2" Type="http://www.w3.org/2001/04/xmlenc#Content" MimeType="text/xml" Encoding="UTF-8">
         <ns1:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
         <ns1:CipherData>
            <ns1:CipherValue>oMNKOEIew22gfa7nx8nUEkYmu0Ksw+lrwxJUJyEfNxjYH0ugkZ8eJv3AAvz0HIv89HKc+ij3Og1o9ncFnFN0DD805ju441DUDBiRleOvy9E=</ns1:CipherValue>
         </ns1:CipherData>
      </ns1:EncryptedData>
   </env:Body>
</env:Envelope>

Testing secure webservice on Weblogic using SOAP UI

Create  the certificates for the client using keytool and store it at a location. You can refer our articles on SSL to get more details on how to create keystores. Once the client keystore is created you need to do the following configuration on SOAP UI.

 

client-keystore

 

outgoing-timestampoutgoing-signature

 

 

Once you’ve done the security configuration you should be able to invoke your secure service

 

request-response

 

REQUEST

 

<soapenv:Envelope xmlns:bea="http://www.bea.com" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header><wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><wsse:BinarySecurityToken EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" wsu:Id="CertId-974A598A574C09B5B614031710223477" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">MIICYTCCAgugAwIBAgIQsAtcv4jhs9Rpsu6mxuT69jANBgkqhkiG9w0BAQQFADB5MQswCQYDVQQGEwJVUzEQMA4GA1UECBMHTXlTdGF0ZTEPMA0GA1UEBxMGTXlUb3duMRcwFQYDVQQKEw5NeU9yZ2FuaXphdGlvbjEZMBcGA1UECxMQRk9SIFRFU1RJTkcgT05MWTETMBEGA1UEAxMKQ2VydEdlbkNBQjAeFw0wNDEwMDMxNjIzNTdaFw0xOTEwMDQxNjIzNTdaMHYxCzAJBgNVBAYTAlVTMRAwDgYDVQQIFgdNeVN0YXRlMQ8wDQYDVQQHFgZNeVRvd24xFzAVBgNVBAoWDk15T3JnYW5pemF0aW9uMRkwFwYDVQQLFhBGT1IgVEVTVElORyBPTkxZMRAwDgYDVQQDFgd1c2VyX2QxMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDbn/m11lE1LDIw/MybKhvDFT8RhVx+ImoV/l85J2BsWWFZAeaM2LPmC/vMcsnptR4XVEGLKtUz5KN8LD388DKkJKXpAwTPMkGtqzOLmNpL4ZKtMgCR0dVqxAqd+ZhuhBJsWPi2r6dnsSumzMNm8U1Rtn8Qve5s6GplPOVLAuD81QIDAQABoy4wLDAqBgNVHQ4EIwQhdGVzdF9jbGllbnRfMTIzNDU2Nzg5MF8wOTg3NjU0MzIxMA0GCSqGSIb3DQEBBAUAA0EAQrN57Of9U2JZOI82G02pYr3zMwvurz3SdsAOI/dh9ctmRMynVYi3vDC8xrZBeMN7+nPZwS+Tb67QA89RI+EdGQ==</wsse:BinarySecurityToken><ds:Signature Id="Signature-8" 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="#id-9">
<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>fSztcx6n1FRtd6IY01CVwaQQKBA=</ds:DigestValue>
</ds:Reference>
<ds:Reference URI="#Timestamp-7">
<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>3OKIlCCMbaIigZvmwM3bB6mwQj0=</ds:DigestValue>
</ds:Reference>
<ds:Reference URI="#CertId-974A598A574C09B5B614031710223477">
<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>+wobq47cIXzuDHyINGRQwnhI5Fg=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>
ivZKz9J7MP15DmrEgZhqdnkrg09+toBNTtUDHBMf+J9wmJOiVRomM10jZ+6SeqIrLSeowbp6q3Ih
uGjkwGAfX6EapHbWNinTkzUCC+i3T9e3HiZdChiEf5f6/b3Lpk+ZaOTmk6IsdIW4gTaxBefY7d5l
xJOUe7p5yKOuzWcMEJk=
</ds:SignatureValue>
<ds:KeyInfo Id="KeyId-974A598A574C09B5B614031710223488">
<wsse:SecurityTokenReference wsu:Id="STRId-974A598A574C09B5B614031710223489" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><wsse:Reference URI="#CertId-974A598A574C09B5B614031710223477" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"/></wsse:SecurityTokenReference>
</ds:KeyInfo>
</ds:Signature><wsu:Timestamp wsu:Id="Timestamp-7" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><wsu:Created>2014-06-19T09:43:42.335Z</wsu:Created><wsu:Expires>2014-06-19T11:07:02.335Z</wsu:Expires></wsu:Timestamp></wsse:Security></soapenv:Header>
   <soapenv:Body wsu:Id="id-9" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
      <bea:sayHello>
         <bea:s>Faisal</bea:s>
      </bea:sayHello>
   </soapenv:Body>
</soapenv:Envelope>

RESPONSE

 

<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
   <env:Header />
   <env:Body>
      <m:sayHelloResponse xmlns:m="http://www.bea.com">
         <m:return>Hello Faisal</m:return>
      </m:sayHelloResponse>
   </env:Body>
</env:Envelope>

Please feel free to comment if you any additional details.

Cheers!
Wonders Team

Webservice Security – WS-Trust and WS-SecureConversation an overview

Webservices

“A Web Service is a system designed to support interoperable communication from machine to machine over a network. It includes an interface described in a machine-processable format (WSDL), and is typically conveyed using HTTP with XML serialization.”
Webservices exist in a wide range of architecture, technologies and software design. They provide an interaction mechanism between Business to Business applications. Webservices rely on SOAP Protocol for the interaction between the B2B applications. SOAP is and XML Based protocol that uses HTTP as its base transport protocol. Following is an example of a SOAP Request and SOAP Response

 

REQUEST

 

POST /SecureHelloWorldService/SecureHelloWorldService

HTTP/1.1 User-Agent: BEA WebLogic Server 10.3.0.0

Content-Type: text/xml; charset=utf-8 SOAPAction: “”

Host: 127.0.0.1:7000

Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2

Connection: keep-alive Content-Length: 187

 

<env:Envelope xmlns:env=”http://schemas.xmlsoap.org/soap/envelope/”>

<env:Header />

<env:Body>

<m:sayHello xmlns:m=”http://www.bea.com”>

<m:s>World</m:s>

</m:sayHello>

</env:Body>

</env:Envelope>

 

RESPONSE

 

HTTP/1.1 200 OK Date: Tue, 24 Jan 2012 06:15:42 GMT

Transfer-Encoding: chunked

Content-Type: text/xml; charset=utf-8

SOAPAction: “” X-Powered-By: Servlet/2.5 JSP/2.1

 

<env:Envelope

xmlns:env=”http://schemas.xmlsoap.org/soap/envelope/”>

<env:Header />

<env:Body>

<m:sayHelloResponse xmlns:m=”http://www.bea.com”>

<m:return>Hello World</m:return>

</m:sayHelloResponse>

</env:Body>

</env:Envelope>

 

Webservices Security

For a secure environment data exchange cannot happen in clear text as sensitive information might be exchanged. Also securing the communication channel for all communication is an overhead and might not be acceptable in all scenarios. Hence many specifications exist which allows to secure the data exchanged. One such framework is WS-Policy which defines how secure messages can be exchanged. To demonstrate this I have secured the above Webservice using standard policies and captured the SOAP Request and SOAP Response

 

@Policies({    @Policy(uri=”policy:Auth.xml”, direction=Policy.Direction.inbound),    @Policy(uri=”policy:Sign.xml”),    @Policy(uri=”policy:Encrypt.xml”)})

 

The message body is encrypted

<env:Body wsu:Id=”Body_FE10KgY262Y31ZRm” xmlns:wsu=”http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd”>

<ns1:EncryptedData Id=”3ZpXu9BlqgQNKF4s” Type=”http://www.w3.org/2001/04/xmlenc#Content” MimeType=”text/xml” Encoding=”UTF-8″ xmlns:ns1=”http://www.w3.org/2001/04/xmlenc#”> <ns1:EncryptionMethod Algorithm=”http://www.w3.org/2001/04/xmlenc#tripledes-cbc” /> <ns1:CipherData> <ns1:CipherValue> T7MoCfhyDwXRjLrpRhZ62es3qK2jhTbY2ReS1ZSWhRaBidi8DwW5EbzNQKgudtPa8m7zxkW/ljebMV5dSvIZrJC1o+6peC111iFgPC4jMyA= </ns1:CipherValue>

</ns1:CipherData>

</ns1:EncryptedData>

</env:Body>

 

In addition to this, security tokens need to be passed for authentication and authorization purpose.

Username Password Token

<wsse:UsernameToken wsu:Id=”unt_CQbnapvDgXSDnTtZ” xmlns:wsu=”http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd”> <wsse:Username>weblogic</wsse:Username>

<wsse:Password Type=”http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText”> weblogic </wsse:Password>

</wsse:UsernameToken>

 

Binary Security Token

<wsse:BinarySecurityToken wsu:Id=”bst_MIWyV2RKFBlLh9AT”xmlns:wsu=”http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd”ValueType=”http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3″EncodingType=”http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary”>MIICYTCCAgugAwIBAgIQsAtcv4jhs9Rpsu6m…..

…………………………………………………………………………………xuT69jAN

BgkqhkiG9w0BAQQFADB5MQswCQYDVQQGEwJVUzEQM

/wsse:BinarySecurityToken>

 

Following is the lists of supported tokens that can be used for authentication and authorization purposes

Lists of tokens (Table 1)

Table 1

Token Type Description
User Name Token-Plain Carries basic information (username and a clear text password or shared secret) for purposes of authenticating the user identity to the WSP. Communication is done in plain text so SSL over HTTPS transport must be used to protect the credentials.
Kerberos Token Carries basic information (username and, optionally, a password or shared secret), in a Kerberos token, for purposes of authenticating the user identity to the WSP.
X.509 Token Contains an X.509 formatted certificate for authentication using credentials created with a public key infrastructure (PKI). In this case, the WSC and WSP must trust each other’s public keys or share a common, trusted certificate authority.
SAML-Holder-Of-Key Token Uses the SAML holder-of-key confirmation method whereby the WSC supplies a SAML assertion with public key information as the means for authenticating the requester to the web service provider. A second signature binds the assertion to the SOAP payload. Can use either SAML v1.x or SAML v2.
SAML-Sender Vouches Token Uses the SAML sender-vouches confirmation method whereby the WSC adds a SAML assertion and a digital signature to a SOAP header. A sender certificate or public key is also provided with the signature. Can use either SAML v1.x or SAML v2.

 

Key Exchange using WS-Trust

In the model above it’s the responsibility of the server to validate the tokens, signatures and perform authentication and authorization. This again can be an overhead, especially if the numbers of clients are very high. Also if the client is not known to the Service, it becomes difficult to establish a trust with the client. To address this situation WS-Trust standard has been adopted.  In this model, the responsibility of establishing the trust has been assigned to a third party. Clients request for a Security Token from a Secure Token Server (STS). Once they get the token, they present the token to the Service. The exchange mechanism and standard format of the token has been provided in WS-Trust specification.  In my test, I used opensso (an open source STS Server) and captured the request-response interaction as depicted in Figure below.

 



1)Client requests for a Security token to a Secure Token Server

<soap:Envelope  xmlns:wsa=”http://schemas.xmlsoap.org/ws/2004/08/addressing”  xmlns:wsu=”http://schemas.xmlsoap.org/ws/2002/07/utility”  xmlns:wsse=”http://schemas.xmlsoap.org/ws/2002/12/secext”  xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/”>

<soap:Header>      <wsa:To>http://demo</wsa:To>

<wsse:Security soap:mustUnderstand=”1″>  ….      </wsse:Security>    </soap:Header>    <soap:Body wsu:Id=”Id-d7fceab4-62ed-45fb-bc09-69310ff1712e”>      <wsse:RequestSecurityToken>        <wsse:TokenType>wsse:SecurityContextToken</wsse:TokenType>        <wsse:RequestType>wsse:ReqIssue</wsse:RequestType>        <wsp:AppliesTo xmlns:wsp=”http://schemas.xmlsoap.org/ws/2002/12/policy”>          <wsa:EndpointReference>            <wsa:Address>http://localhost:7001//SecureHelloWorldService/SecureHelloWorldService</wsa:Address>          </wsa:EndpointReference>

</wsp:AppliesTo>

</wsse:RequestSecurityToken>    </soap:Body>

</soap:Envelope>

2)Secure Token Server provides the token to the Client.

<soap:Envelope xmlns:wsa=”http://schemas.xmlsoap.org/ws/2004/08/addressing”  xmlns:wsu=”http://schemas.xmlsoap.org/ws/2002/07/utility”  xmlns:wsse=”http://schemas.xmlsoap.org/ws/2002/12/secext”  xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/”>

<soap:Header>      <wsse:Security soap:mustUnderstand=”1″> ….

</wsse:Security>

</soap:Header>    <soap:Body wsu:Id=”Id-aa53632b-2211-46c8-451-4234b12ecf834″>

<xenc:EncryptedData xmlns:xenc=”http://www.w3.org/2001/04/xmlenc#”>        <xenc:EncryptionMethod Algorithm=”http://www.w3.org/2001/04/xmlenc#tripledes-cbc” />        <xenc:CipherData>          <xenc:CipherValue>…

</xenc:CipherValue>

</xenc:CipherData>

</xenc:EncryptedData>

</soap:Body>  </soap:Envelope>

3)Using the token, the service is invoked.

<soap:Envelope xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/”  xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”  xmlns:xsd=”http://www.w3.org/2001/XMLSchema”  xmlns:wsa=”http://schemas.xmlsoap.org/ws/2004/08/addressing”  xmlns:wsu=”http://schemas.xmlsoap.org/ws/2002/07/utility”  xmlns:wsse=”http://schemas.xmlsoap.org/ws/2002/12/secext”>

<soap:Header>      <wsa:To>http://quoteservice</wsa:To>

<wsse:Security soap:mustUnderstand=”1″> ….      </wsse:Security>

</soap:Header>    <soap:Body wsu:Id=”Id-aa53632b-2211-46c8-451-4234b12ecf834″>

<xenc:EncryptedData xmlns:xenc=”http://www.w3.org/2001/04/xmlenc#”> …

</xenc:EncryptedData>    </soap:Body>

</soap:Envelope>

 

4)Response from the service

<soap:Envelope xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/”  xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”  xmlns:xsd=”http://www.w3.org/2001/XMLSchema”  xmlns:wsa=”http://schemas.xmlsoap.org/ws/2004/08/addressing”  xmlns:wsu=”http://schemas.xmlsoap.org/ws/2002/07/utility”>    <soap:Header>    </soap:Header>    <soap:Body>       <m:sayHelloResponse xmlns:m=”http://www.bea.com”>

<m:return>Hello World</m:return>       </m:sayHelloResponse>

</soap:Body>

</soap:Envelope>

 

References

1) Webservices Vulnerabilities, Security Compass Inc 2007
2) WS Trust Specification
http://specs.xmlsoap.org/ws/2005/02/trust/WS-Trust.pdf
3) WS Security Specification
http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0.pdf
4) Open SSO STS Solution
http://en.wikipedia.org/wiki/OpenSSO
http://www.oracle.com/technetwork/testcontent/opensso-091890.html

Securing WebServices using Username / Password mechanism

Security is an important aspect of your application design. When the web services are deployed and accessed, you might like to restrict its accesses to particular set of users/ groups or any users of a particular role. Hence we specify the policies for the application  webservice in this case at the transport level.

WebServices can be secured using the below mechanisms:

Transport-level security secures the connection between the client application and WebLogic Server with Secure Sockets Layer (SSL). SSL provides secure connections by allowing two applications connecting over a network to authenticate the other’s identity and by encrypting the data exchanged between the applications. Authentication allows a server, and optionally a client, to verify the identity of the application on the other end of a network connection. A client certificate (two-way SSL) can be used to authenticate the user.

Encryption makes data transmitted over the network intelligible only to the intended recipient.

Transport-level security includes HTTP BASIC authentication as well as SSL.

Message-Level Security refers to securing some or all of the message content, which relies on the WS-Security specification. WS-Security provides support for encrypting and/or signing part or all of a message. It also provides authentication using token-based credentials. In addition to WS-Security, WebLogic Server also supports the WS-SecureConversation standard to enable a secure session to be established between two trusted parties to facilitate the exchange of multiple messages in a stateful and secure manner.

Access control security answers the question “who can do what?” First you specify the security roles that are allowed to access a Web Service; a security role is a privilege granted to users or groups based on specific conditions. Then, when a client application attempts to invoke a Web Service operation, the client authenticates itself to WebLogic Server, and if the client has the authorization, it is allowed to continue with the invocation. Access control security secures only WebLogic Server resources. That is, if you configureonly access control security, the connection between the client application and WebLogic Server is not secure and the SOAP message is in plain text

 

The below post describes a demonstration of simple username/password-based authentication for webservices.

Pre-requisites :

1: WebService  deployed.

You can refer the below posts to create a sample WebService and a Java stand alone client to access the same.

http://weblogic-wonders.com/weblogic/2011/05/20/webservice-by-bottom-up-approach-using-ant-script/

http://weblogic-wonders.com/weblogic/2011/05/23/creating-stand-alone-webservice-client-from-wsdl/

 

Please follow the steps below:

1. Defining security poilicies:

Define the  policies to the WebService from the console:-

Go to Deployments –> WebService application deployed –> Security –> Policies. From the predicate list select a User / Group/ Role who can access the WebService.

Click save to create the security policy for the WebService.

2: Test the setup:

If you access the WebService without proper credentials, then you would experience the below error.

Exception in thread "main" javax.xml.ws.soap.SOAPFaultException: Access denied to operation sayHelloWorld

at com.sun.xml.ws.fault.SOAP11Fault.getProtocolException(SOAP11Fault.java:188)

at com.sun.xml.ws.fault.SOAPFaultBuilder.createException(SOAPFaultBuilder.java:116)

at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:119)

at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:89)

at com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:118)

at $Proxy29.sayHelloWorld(Unknown Source)

at com.test.webservice.client.Main.main(Main.java:17)

Caused by: javax.xml.ws.soap.SOAPFaultException: Access denied to operation sayHelloWorld

at weblogic.wsee.jaxws.security.AuthorizationTube.processRequest(AuthorizationTube.java:189)

In the java client, specify the user credentials to access the WebService as below.

Map<String, Object> rc = ((BindingProvider)port).getRequestContext();

rc.put(BindingProvider.USERNAME_PROPERTY, "weblogic");

rc.put(BindingProvider.PASSWORD_PROPERTY, "weblogic");

The JAX-WS BindingProvider class contains username and password properties that we set to specifythe user’s credentials. The underlying web service stub takes care of base 64 encoding these credentials and including them in the HTTP headers of the SOAP request.

A typical java standalone client would look like below.

 

import com.test.webservice.client.*;

import java.util.Map;

import javax.xml.ws.BindingProvider;

public class Main {

public static void main(String[] args) {

com.test.webservice.client.HelloWorldService service = new com.test.webservice.client.HelloWorldService();

com.test.webservice.client.HelloWorldPortType port = service.getHelloWorldPortTypePort();

Map<String, Object> rc = ((BindingProvider)port).getRequestContext();

rc.put(BindingProvider.USERNAME_PROPERTY, "weblogic");

rc.put(BindingProvider.PASSWORD_PROPERTY, "weblogic");

String result=port.sayHelloWorld(" Anandraj ");

System.out.println("********* RESULT from WebService ***********");
System.out.println(result);

System.out.println("********************************************");
}

}

 

Compile and execute the java client, then you would be able to invoke the secured WebService successfully.

You can refer the below link for securing the WebService using the Basic Authentication:

http://weblogic-wonders.com/weblogic/2010/01/04/securing-webservices-using-basic-authentication-on-weblogic-server/

For further reading :

http://download.oracle.com/docs/cd/E12840_01/wls/docs103/webserv_sec/message.html

Regards,

Wonders Team. 🙂