Saturday, January 24, 2015

Read the content stored in registry- WSO2 ESB


1.Lets say we have stored a XML file (order-id.xml) in registry.



2. I'm going to use Mock Service (Mockproxy) to read the content  and send back as a response (using respond mediator -ESB 4.8.x).

<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="Mockproxy"
       transports="https,http"
       statistics="disable"
       trace="disable"
       startOnLoad="true">
   <target>
      <inSequence>
         <property name="order"
                   expression="get-property('registry','conf:/order-id.xml')"
                   scope="default"
                   type="OM"/>
         <payloadFactory media-type="xml">
            <format>
               <response>
                  <id>$1</id>
                  <symbol>$2</symbol>
               </response>
            </format>
            <args>
               <arg evaluator="xml" expression="$ctx:order//id"/>
               <arg evaluator="xml" expression="$ctx:order//symbol"/>
            </args>
         </payloadFactory>
         <respond/>
      </inSequence>
   </target>
   <description/>
</proxy>
3. Mockproxy test.

Request :
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
   <soapenv:Body></soapenv:Body>
</soapenv:Envelope>
Response:

<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
   <soapenv:Body>
      <response xmlns="http://ws.apache.org/ns/synapse">
         <id>1</id>
         <symbol>WSO2</symbol>
      </response>
   </soapenv:Body>
</soapenv:Envelope>

Monday, January 19, 2015

How WS-Trust STS works in WSO2 Identity Server.


WS-Trust STS (Secure Token Service) provides the facility for  secure communication between web service client and server.




Benefits of WS-Trust STS

1. Identity delegation.
2. Service consumers should not be worried about the token specific implementation/knowledge.
3. Secure communication across  the web services.

Work flow.

1. Service client provides credentials to STS and request a security token (RST - Request Security Token).

2. STS validates the client credentials and reply with security token (SAML) to the client (RSTR -Request Security Token Reply).

3. Client invoke the web service along with the token.

4. Web service validates the  token from the STS.

5. STS send the decision to the web service.

6. If the token is valid web service allow to access the protected resource(s).

Use Case

Invoke a secured  web service  (Hosted in WSO2 Application Server) using the secure token issued by WSO2 Identity Server.

1. Download the latest version of WSO2 AS (5.2.1) and WSO2 Identity Server(5.0.0).
2. In AS,  change the port offSet value in carbon.xml to 1 (default 0).
3. Start both servers.
4. The "HelloService" sample web service which is already deployed in AS.

 
 5. Once you chick on the "HelloService" name, you should see the service endpoints.



6. In this use case we are going to use the "wso2carbon-sts" service of the Identity Server for issuing and validating tokens. Therefore Identity server act as the "Identity Provider". So we need to configure the Resident Identity Provider" first.

7. Go to Home ---> Identity -----> Identity Provider -----> List, then  click on "Resident Identity Provide" link.

8. Add a name for the resident Identity provider. (Eg: "WSO2IdentityProvider")


9. Expand the "WS-Trust / WS-Federation (Passive) Configuration". Now you should see the "wso2carbon-sts" endpoint.


10. Click on the "Apply Security Policy" link and enable the security. Then select the security scenario which is need to be applied for the wso2carbon-sts service. (Eg: select UsernameToken). Once you select the security scenario, the relevant policy will be applied automatically to the "wso2carbon-sts" service.




 10. Select the user group(s) which is allowed to access the "wso2carbon-service" for requesting  tokens.


11. Click on the "wso2carbon-sts" service link, now you should  see the wsdl including the applied policy.

https://localhost:9443/services/wso2carbon-sts





12.To add a service provider for web service client , enter name (eg : HelloServiceProvider) for the new service provider and update.




13. Edit the "HelloServiceProvider" and configure the web service.







14. Apply the security for the "HelloService" deployed in AS.


15. Select the  "Non-Repudiation" as the security scenario.

   Bellow image is captured from Identity Server product.




16. Now  "HelloService" WSDL should have the applied policy.


17. Download the sts-client project from following git repository location.
(This is same sample which is included in the WSO2 Identity Server  project and did few changes for this use case).

git : https://github.com/ajithnv/blog_resources/tree/master/sts-client


18 README of the sts-client project describes how to execute the client.


(The underline values should be changed according to your environment.)

19. The key store of the web service client  should have the public certificate of the STS and AS. Therefore it used the wso2carbon.jks which is already using in ESB and AS.

20 You can enable the soap tracer to capture the request and reply of each servers.





Wednesday, January 14, 2015

Adding custom password policy enforcer to WSO2 Identity Server.

1. Lets say, user password should meet the following requirements

* password should have at least one lower case
* password should have at least one upper case
* password should have at least one digit
* password should have at least one special character (!@#$%&*).
* password should have 6-8 characters.

 You can write new custom password enforcer extending the AbstractPasswordPolicyEnforcer class.

1. You can download the java project from following git repository location [i]

[i]https://github.com/ajithnv/blog_resources/tree/master/passwordpolicy

2. Build the project (Follow the README.txt).

3. Copy the jar file in to <IS5.0.0_HOME>/repository/components/lib directory.

4. Open the identity-mgt.properties file (<IS5.0.0_HOME>/repository/conf/security/identity-mgt.properties).

5. Enable the  identity listener.

Identity.Listener.Enable=true

6. Disable the default Password.policy.extensions configurations.

#Password.policy.extensions.1=org.wso2.carbon.identity.mgt.policy.password.DefaultPasswordLengthPolicy
#Password.policy.extensions.1.min.length=6
#Password.policy.extensions.1.max.length=12
#Password.policy.extensions.2=org.wso2.carbon.identity.mgt.policy.password.DefaultPasswordNamePolicy
#Password.policy.extensions.3=org.wso2.carbon.identity.mgt.policy.password.DefaultPasswordPatternPolicy
#Password.policy.extensions.3.pattern=^((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%&*])).{0,100}$

7. Add new configuration for custom policy enforcer.

Password.policy.extensions.1=org.sample.policy.CustomPasswordPolicyEnforcer
Password.policy.extensions.1.pattern=^((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%&*])).{6,8}$

8. Restart the server.

9. Test.

i) user : ajith  password : 1Acws@d  (this password meet above  policy).


ii) user : ajith1 password : 1Acws@dgggg (this password doesn't meet above policy because length is  11.)







Tuesday, January 13, 2015

SOAP web service as REST API using WSO2 API Manager -1

Pre-requirement:

Download the latest version of   WSO2 API Manager ,WSO2 Application Server and WSO2 Developer Studio from wso2.com web site.

1. Deploy sample web service.
1.1 Open the carbon.xml file and changed the port off set value to 1, then start the server. (carbon.xml file under the wso2as-5.2.1/repository/conf directory)
 
 <Offset>1</Offset>

1.2. Log in to the administrator console(admin/admin) and deploy the SimpleStockQuoteService.aar file using aar file deploying wizard. (Please check the bellow image)

https://[host or IP]:9444/carbon/

1.3 Download this sample web service archive[i] (SimpleStockQuoteService.aar) and deploy on WSO2 Application Sever.

[i] : https://github.com/ajithnv/blog_resources/tree/master/soaptorest



 1.4 After few seconds refresh the service "List" page, now you should see the "SimpleStockQuoteService" service in the services list. (Please see bellow image)


1.5 Click on the "SimpleStockQuoteService" name, now  you should see the  WSDL locations(1) and endpoints(2) of that services along with some other features.


1.6 Create a SOAP UI project and invoke some operation. (as an example I'm going to invoke the getQuote operation)



1.7 Now I'm going to expose this operation(getQuote)  using WSO2 API Manager.

GET : http://<Host or IP>:<port>/stockquote/1.0.0/getquote?name=IBM

2.0 Create ESB configuration project

WSO2 Developer Studio(DevS)  provides rich graphical editor to create a message mediation flow without writing XML configuration by hand.

2.1 File --> New project ---> Other , then select the "ESB Config Project" and create new esb config project called 'ESBConfigProject'.

[You can find my project in following git repository location [i]. (Download and import that to DevS)]

[i] https://github.com/ajithnv/blog_resources/tree/master/soaptorest

This is to create the back-end payload at the in sequence which is expecting from the StockQuoteService.



When you switch to the "source" view , you should see the following configuration.

<?xml version="1.0" encoding="UTF-8"?>
<sequence xmlns="http://ws.apache.org/ns/synapse" name="admin--StockQuoteAPI:v1.0.0--In">
    <payloadFactory media-type="xml">
        <format>
            <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://services.samples/xsd" xmlns:ser="http://services.samples">
                <soapenv:Header/>
                <soapenv:Body>
                    <ser:getQuote>
                        <!--Optional:-->
                        <ser:request>
                            <!--Optional:-->
                            <xsd:symbol>$1</xsd:symbol>
                        </ser:request>
                    </ser:getQuote>
                </soapenv:Body>
            </soapenv:Envelope>
        </format>
        <args>
            <arg xmlns:m0="http://services.samples/xsd" evaluator="xml" expression="$url:name"/>
        </args>
    </payloadFactory>
</sequence>


Following sequence  is to convert  the message format to JSON at the out sequence.


When you switch to the "source" view , you should see the following configuration.

<?xml version="1.0" encoding="UTF-8"?>
<sequence xmlns="http://ws.apache.org/ns/synapse" name="admin--StockQuoteAPI:v1.0.0--Out">
    <property name="messageType" value="application/json" scope="axis2" type="STRING"/>
</sequence>

3. Create new composite application project  in developer studio to build a carbon archive. (Select the ESBConfigProject project at the creation flow )




4. Use the top right conner button to export as .car file (ESBCARApp_1.0.0.car).


5. Create new server role called EnterpriseServiceBus in API manager(This is to deploy the ESB car file in API Manager).



6. Create new deployment directory called "carbonapps" inside the  wso2am-1.9.0/repository/deployment/server/ directory.

7. Copy the ESBCARApp_1.0.0.car file to wso2am-1.9.0/repository/deployment/server/carbonapps directory. (This car file will deploy the above two sequences in API Manager)

8. 1) Create new  API in API manager.

Name    : StockQuoteAPI
Context : stockquote
Version : 1.0.0
Resource method : getquote
Query parameter : name



8.2) Select the  endpoint type  as "Address Endpoint" (http://localhost:9764/services/SimpleStockQuoteService/).



8.iii) Click on the "Advance Options" and select the message format as "SOAP 1.1".


8.iv) Go to the manage wizard , select the tier and "save & publish".




9. Go to the store , subscribe API to an application , generate a token.



10. Invoke API from SOAP UI. (Make sure to add the Authorization and SOAPAction as the headers)



11. The response message format should be JSON.
{"getQuoteResponse": {"return": {
   "@type": "ax23:GetQuoteResponse",
   "change": 3.8029902107822418,
   "earnings": -9.840572906863278,
   "high": -78.83716414296619,
   "last": 80.02780758052141,
   "lastTradeTimestamp": "Wed Aug 26 16:17:20 EDT 2015",
   "low": -78.09783867850369,
   "marketCap": 5555207.279685723,
   "name": "IBM Company",
   "open": 82.90256019282909,
   "peRatio": -18.258083449962875,
   "percentageChange": -4.95172669142163,
   "prevClose": -76.80129473564324,
   "symbol": "IBM",
   "volume": 5049
}}}

Related posts:

ii) http://www.vitharana.org/2015/08/soap-webservice-as-rest-api-wso2-api.html

iii) http://www.vitharana.org/2015/08/advance-mediation-with-wso2-api-manager.html

Saturday, January 10, 2015

Adding namespace and prefix to only root tag using XSLT

1. Lets assume that we have following XML content.

<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
   <soapenv:Body>
    <ByExchangeRateQuery>  
    <MessageHeader>  
        <CreationDateTime></CreationDateTime>  
    </MessageHeader>  
    <ExchangeRate>  
        <rateCode>M</rateCode>  
        <CurrencyUnit>*</CurrencyUnit>  
        <Currency>*</Currency>  
        <DateTime>2014-06-10T02:27:36Z</DateTime>  
    </ExchangeRate>  
</ByExchangeRateQuery>
   </soapenv:Body>
</soapenv:Envelope>
2. Add the namespace and prefix only for the root tag.
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
   <soapenv:Body>
      <ns0:ByExchangeRateQuery xmlns:ns0="http://test.com/test/wso2/blog/Sample">
         <MessageHeader>
            <CreationDateTime/>
         </MessageHeader>
         <ExchangeRate>
            <rateCode>M</rateCode>
            <CurrencyUnit>*</CurrencyUnit>
            <Currency>*</Currency>
            <DateTime>2014-06-10T02:27:36Z</DateTime>
         </ExchangeRate>
      </ns0:ByExchangeRateQuery>
   </soapenv:Body>
</soapenv:Envelope>

3. Define the XSLT file.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>
    <!--match all the nodes and attributes-->
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*">
        </xsl:apply-templates></xsl:copy>
    </xsl:template>
    <!--Select the element need to be apply the namespace and prefix -->
    <xsl:template match="ByExchangeRateQuery">
        <!--Define the namespace with prefix ns0 -->
        <xsl:element name="ns0:{name()}" namespace="http://test.com/test/wso2/blog/Sample">
            <!--apply to above selected node-->
            <xsl:apply-templates select="node()|@*">
        </xsl:apply-templates></xsl:element>
    </xsl:template>
</xsl:stylesheet>