Sunday, September 21, 2014

Leveraging federation capabilities of Identity Server for API gateway - Configuration Details

With this post I am to share the steps of a popular solution using WSO2 Identity Server and WSO2 API Manager. Following diagram will give an initial insight on this solution.


1.  Webapp that requires single sign on(SSO) facility with some other applications. 
                - To achieve this we are using WSO2 Identity Server(IS) as the Identity Provider(IDP). 

2.  Webapp needs to consume some APIs secured with OAuth tokens. 
                - To expose the APIs secured with OAuth tokens we are using WSO2 API Manager(AM) here.
                - Since we already have the SAML Response received at SSO step, SAML2 Bearer grant type is ideal to use at this scenario to request an OAuth token to access the required APIs.
                - Allowing AM to properly issue an OAuth token in this scenario, we add IS as a trusted IDP in AM.

3.  Webapp requires to allow users registered in another IDP like Facebook or Google to be able to login with SSO functionality. 
                - With minimum configurations to internal IS and external IDP side, we need to achieve this.
Rest of this post will deal with how we can configure the above, without sharing any databases underneath. Will setup this in multi-tenancy mode, to make it a more general scenario. Another instance of WSO2 Identity Server will be used in the place of external IDP. This can be replaced with Facebook, Google etc. according the requirement.


WSO2 Identity Server -5.0.0 -
WSO2 API Manager 1.7.0 -
                             The compiled webapp ready to deploy in a servelet container, can be found here.
As we are to run several instances of WSO2 servers we need to configure port offsets, if all are configured in one machine. Following are the port offsets and ports I am to use. I will be using two tenants in the two Identity servers and API manager will be run of super tenant mode.

1. WSO2 Identity Server -5.0.0 - Internal IDP - Offset 0 - Port 9443 
                 Tenant -
2. WSO2 Identity Server -5.0.0 - Internal IDP - Offset 1 - Port 9444 
                 Tenant -
3. WSO2 API Manager 1.7.0 - API Gateway - Offset 2 - Port 9445
                 Tenant - carbon.super

Webapp Configurations 

If you download the webapp from the above link, the keystore configurations are already done. You will only need to import the public certificate of the tenant in internal IDP( to the keystore of webapp 'travelocity.jks'. 
Please note the following configurations done in file found inside webapp at '/'.


#A unique identifier for this SAML 2.0 Service Provider application

#The URL of the SAML 2.0 Identity Provider

#Password of the KeyStore for SAML and OpenID

#Alias of the IdP's public certificate

#Alias of the SP's private key 

#Private key password to retrieve the private key used to sign 
#AuthnRequest and LogoutRequest messages

#OAuth2 token endpoint URL

#OAuth2 Client ID

#OAuth2 Client Secret

1. SSO Setup with Internal IDP

  • Login as tenant admin - <admin>
  • Export the public certificate of the private key used at webapp side to sign the SAML Authentication Request. Following command can be used to export it.
keytool -export -alias travelocity -file travelocity -keystore <path to travelocity.jks(which ever keystore used at webapp side)>
  • Import the above exported public certificate to the tenant key store of the internal IDP, identity server as below.

  • After the import it will listed as below.

  • Create a new Service Provider for Travelocity webapp as following.
  • Then we needs to configure it as below.    
- By enabling SaaS application, we are removing the tenant boundary for this service provider.
- Enable response and assertion signing according to your requirement.
- Enable signature verification for SAML Authentication Request

The configurations are mostly done to get the SSO scenario work with the webapp. We need to export the tenant public certificate to be imported to the trust store at webapp side. This is in order to verify the SAML Response/Assertion signed signature at the webapp side. We can export the certificate as below from the UI, using public key link.


The exported key needs to be imported to webapp truststore(in this case travelocity.jks we located inside the webapp).

keytool -import -alias <The given alias name. Here> -file <path to downloaded public certificate> -keystore <path to trust store of webapp. Here the travelocity.jks file>

Now if you try to login to travelocity web app as a tenant user, it should succeed.

2. External federation

Following configuration will demonstrate how to configure an external identity provider in Identity Server. Here we will use another instance of identity server as the external IDP. The scenario will be extended from the previous scenario. 

At internal federation, we had 'Travelocity' webapp registered as a Service Provider in the IDP which decided the authenticity of user. Now we will federate the decision on the authenticity of the user to an external IDP. For the demonstration purposes I am using a tenant(named in the external IDP(

Configuring another IS instance to act as an external IDP (

  • Create a tenant named ‘’ and login with this tenant.
  • First we need to import the public certificate of the internal IS into tenant key store, which is paired with the private key used to sign the SAML Request. This time it is 'wso2carbon'.
  • Configure the internal IS as a service provider here. This is because now the SAML request is to be sent to this IS by the internal IS, we configured before.
  • Note that ‘Assertion Consumer URL’ is pointed to ‘https://localhost:9443/commonauth’ of the internal IS. Also note the certificate alias we have selected to use at SAML Request signature validation. This is the one that we imported here.

Configure Internal IS to federate SSO requests from Travelocity webapp to the external IDP

In the internal IS, we need to configure it to make use of the external IDP we just configured.
  • Create a Identity Provider as below. 
  • Upload the public certificate we can download from the external IDP, tenant keystore. This is to validate the signatures of SAML Response and Assertions that will be sent to this internal IS from the external IS.

We have to make some additional changes in the service provider configuration for Travelocity webapp as well. 
  • In the drop down list of federated authenticators select the identity provider we just configured.

There is one more addition we have to do as following to meet the requirement of audience restriction validation in SAML SSO scenario. This is not a requirement for federation, but for API access. The value we give here for audience is the OAuth token endpoint, which we will consume to exchange the SAML token for an OAuth token.

Now we are in a position to test the external federation scenario with Travelocity webapp sample. After hosting it in a tomcat server, hit the URL, ‘http://localhost:8080/’, which will take us to a page as below. Click on the link to login with SAML.

This will take us to following screen. Note the page is from our external IDP (, where we can enter credentials of a user in this IDP to get successfully authenticated. If our external authenticator was Google this will be a page from Google, submitted to enter the credentials.

After successful authentication, following screen will be shown.

Now the external federated SAML scenario is completed.

3. API Access leveraging the federation

To achieve this we need following configurations present at Webapp side.
  • Register an application in API-M store, subscribe to some APIs, provide the generated client id and client secret values in file of the sample webapp.
  • Point SAML.OAuth2TokenEndpoint=https://localhost:9445/oauth2/token to OAuthtoken endpoint of API-M.
  • Import the public certificate of internal IS, to the  keystore used by webapp. The given alias value should be provided at ‘’ in file.

IDP Configuration at API-M

  • Configure ‘host name’ and ‘mgt host name’ in APIM_HOME/repository/conf/carbon.xml 
  • Login as super admin and add an identity provider as following.

  • Following fields needs to be filled. Note that we have imported the public certificate of the internal IS here, so that we can validate it’s SAML token.
  • API-M is not aware of the federation happening at the internal IS node.

  • When configuring the federated authenticator, we should note that Identity Provider entity id should be as same as the issuer of the SAML Response coming to API-M, to exchange for an OAuth token. SSO URL, is the redirect URL for internal IS.

  • Once these configurations are done, we can test the end-to-end scenario. Now from the page we left at ‘Travelocity’ webapp, if we click on the link ‘Request OAuth2 Access Token’ following page will appear. It is showing the details of the OAuth token, it received in exchange to the provided SAML token.

Now we can use this access token at webapp side to consume any APIs we got subscribed to.

Hope this helps. We can expand and customize this scenario in several ways according to requirements, with options provided with federation, provisioning and extension points. Will discuss those in a latter post.


Wednesday, September 10, 2014

How to write a Custom SAML SSO Assertion Signer for WSO2 Identity Server

This is the 3rd post I am writing to explain the use of extension points in WSO2 Identity Server. WSO2 Identity Server has so many such extension points which are easily configurable and arm the server with lot of flexibility. With this, we can support so many domain specific requirements with minimum efforts.
  • Now this third post deals with writing a custom SAML SSO Assertion signer.

What we can customize?

  • Credentials used to sign the SAML Assertion (The private key)
  • Signing Algorithm
  • This sample can be extended to customize how we sign the SAML Response and validate the signature as well.


We have to write a class extending 
  • The class '' or
  • The interface ''
Needs to override the following method in our case to customize how we sign the assertion,


    public Assertion doSetSignature(Assertion assertion, String signatureAlgorithm, X509Credential cred) throws IdentityException {

        try {
            //override the credentials with our desired one
            cred = getRequiredCredentials();
            Signature signature = (Signature) buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);

            try {
                KeyInfo keyInfo = (KeyInfo) buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME);
                X509Data data = (X509Data) buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);
                X509Certificate cert = (X509Certificate) buildXMLObject(X509Certificate.DEFAULT_ELEMENT_NAME);

                String value =
            } catch (CertificateEncodingException e) {
                throw new IdentityException("errorGettingCert");


            List<Signature> signatureList = new ArrayList<Signature>();

            // Marshall and Sign
            MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration
            Marshaller marshaller = marshallerFactory.getMarshaller(assertion);


            return assertion;
        } catch (Exception e) {
            throw new IdentityException("Error while signing the SAML Response message.", e);

Finally we have to update the identity.xml() as below with the above custom class we write overriding the methods.

and place the compiled package with the above class at 'IS_HOME/repository/components/lib' 

Now if we restart the server and run the SAML SSO scenario, the SAML SSO Assertion will be signed in the way we defined at the custom class we wrote.

Here you can find a complete sample code to customize the assertion signing procedure.

Hope this helps..

Thursday, July 31, 2014

Adding Custom Claims to the SAML Response - (How to Write a Custom Claim Handler for WSO2 Identity Server)


The latest release of WSO2 Identity Server (version 5.0.0), is armed with an "application authentication framework" which provides lot of flexibility in authenticating users from various service providers who are using heterogeneous protocols. It has several extension points, which can be used to cater several customized requirements commonly found in enterprise systems. With this post, I am going to share the details on making use of one such extension point.

Functionality to be Extended

When SAML Single Sign On is used in enterprise systems it is through the SAML Response that the relying party get to know whether the user is authenticated or not. At this point relying party is not aware of other attributes of the authenticated user which it may need for business and authorization purposes. To provide these attribute details for the relying party, SAML specification has allowed to send attributes as well in the SAML Response. WSO2 Identity Server supports this out of the box via the GUI provided for administrators. You can refer [1] for the details on this functionality and configuration details.

The flexibility provided by this particular extension, comes handy when we have a requirement to add additional attributes to the SAML Response, apart from the attributes available in the underline user store. There may be external data sources we need to look, in order to provide all the attributes requested by the relying parties. 

In the sample I am to describe here, we will be looking into a scenario where the system needs to provide some local attributes of the user which are stored in user store, with some additional attributes I expect to be retrieved from an external data source.
Following SAML Response is what we need to send to the relying party from WSO2 IS.

<saml2p:Response Destination="https://localhost:9444/acs" ID="faibaccbcepemkackalbbjkihlegenhhigcdjbjk"
                 InResponseTo="kbedjkocfjdaaadgmjeipbegnclbelfffbpbophe" IssueInstant="2014-07-17T13:15:05.032Z"
                 Version="2.0" xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol"
    <saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity"
    <ds:Signature xmlns:ds="">
        <saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
    <saml2:Assertion ID="phmbbieedpcfdhcignelnepkemobepgaaipbjjdk" IssueInstant="2014-07-17T13:15:05.032Z" Version="2.0"
                     xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:xs="">
        <saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">localhost</saml2:Issuer>
        <ds:Signature xmlns:ds="">
          <saml2:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">Administrator</saml2:NameID>
            <saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
                <saml2:SubjectConfirmationData InResponseTo="kbedjkocfjdaaadgmjeipbegnclbelfffbpbophe"
        <saml2:Conditions NotBefore="2014-07-17T13:15:05.032Z" NotOnOrAfter="2014-07-17T13:20:05.032Z">
        <saml2:AuthnStatement AuthnInstant="2014-07-17T13:15:05.033Z">
            <saml2:Attribute Name=""
                <saml2:AttributeValue xmlns:xsi="" xsi:type="xs:string">
                <saml2:Attribute Name=""
                    <saml2:AttributeValue xmlns:xsi="" xsi:type="xs:string">
                <saml2:Attribute Name=""
                    <saml2:AttributeValue xmlns:xsi="" xsi:type="xs:string">

In this response we are having one local attribute, which is role and two additional attributes and which have been retrieved from some other method we can define in our extension.


1. Implement the customized logic to get the external claims. There are just two facts we need to note at this effort.

  • The custom implementation should either implement the interface '' or extend the default implementation of the interface ''.  
  • The map returned at the method, 'public Map<String, String> handleClaimMappings' should contain all the attributes we want to add to the SAML Response.
Following is the sample code I was written, adhering to the above. The external claims may have been queried from a database, read from a file or using any other mechanism as required.

public class CustomClaimHandler implements ClaimHandler {

    private static Log log = LogFactory.getLog(CustomClaimHandler.class);
    private static volatile CustomClaimHandler instance;
    private String connectionURL = null;
    private String userName = null;
    private String password = null;
    private String jdbcDriver = null;
    private String sql = null;

    public static CustomClaimHandler getInstance() {
        if (instance == null) {
            synchronized (CustomClaimHandler.class) {
                if (instance == null) {
                    instance = new CustomClaimHandler();
        return instance;

    public Map<String, String> handleClaimMappings(StepConfig stepConfig,
                                                   AuthenticationContext context, Map<String, String> remoteAttributes,
                                                   boolean isFederatedClaims) throws FrameworkException {

        String authenticatedUser = null;

        if (stepConfig != null) {
            //calling from StepBasedSequenceHandler
            authenticatedUser = stepConfig.getAuthenticatedUser();
        } else {
            //calling from RequestPathBasedSequenceHandler
            authenticatedUser = context.getSequenceConfig().getAuthenticatedUser();

        Map<String, String> claims = handleLocalClaims(authenticatedUser, context);

        return claims;

     * @param context
     * @return
     * @throws FrameworkException
    protected Map<String, String> handleLocalClaims(String authenticatedUser,
                                                    AuthenticationContext context) throws FrameworkException {

    private Map<String, String> getFilteredAttributes(Map<String, String> allAttributes,
                                                      Map<String, String> requestedClaimMappings, boolean isStandardDialect) {

    protected String getDialectUri(String clientType, boolean claimMappingDefined) {

     * Added method to retrieve claims from external sources. This results will be merged to the local claims when
     * returning final claim list, to be added to the SAML response, that is sent back to the SP.
     * @param authenticatedUser : The user for whom we require claim values
     * @return
    private Map<String, String> handleExternalClaims(String authenticatedUser) throws FrameworkException {
        Map<String, String> externalClaims = new HashMap<String, String>();
        return externalClaims;

2.Drop the compiled OSGI bundle at IS_HOME/repository/components/dropins. (We developed this as a OSGI bundle as we need to get local claims as well using RealmService. You can find the complete bundle and source code here)

3. Point WSO2 Identity Server to use the new custom implementation we have.

In IS_HOME/repository/conf/security/application­authentication.xml configure the new handler name. (in 'ApplicationAuthentication.Extensions.ClaimHandler' element.)

Now if look at the generated SAML Response, we will see the external attributes added.

[1] -

Friday, July 18, 2014

Leveraging federation capabilities of Identity Server for API gateway (First Webinar Conducted by Myself)

The first Webinar conducting experience for me happened on July 02nd 2014, with opportunity given  by WSO2 Lanka (pvt) Ltd, where I am currently employed. As always that was a great opportunity given by the company to me.

The Webinar was done to highlight the capabilities introduced with WSO2 IS 5.0.0, the First Enterprise Identity Bus, which is 100% free and open source. This Webinar, in detail discuss and demonstrate the power and value it adds when these capabilities of federation are leveraged in combination with WSO2 API Manager. 

Following are the slides used at the Webinar. 

The session went under following outline and you can watch the full recording of the session at WSO2 library, 'Leveraging federation capabilities of Identity Server for API gateway'.

  • Configuring WSO2 Identity Server as the OAuth2 key manager of the API Manager
  • Identity federation capability of Identity Server 5.0
  • How to connect existing IAM solution with API Manager through identity bridge
  • How to expand the solution to various other possible requirements
Lot more to improve. Any feed backs, suggestions are warmly welcome!

Wednesday, March 05, 2014

Signing SOAP Messages - Generation of Enveloped XML Signatures

Digital signing is a widely used mechanism to make digital contents authentic. By producing a digital signature for some content, we can let another party capable of validating that content. It can provide a guarantee that, is not altered after we signed it, with this validation. With this sample I am to share how to generate the a signature for SOAP envelope. But of course this is valid for any other content signing as well.

Here, I will sign
  • The SOAP envelope itself
  • An attachment 
  • Place the signature inside SOAP header 
With the placement of signature inside the SOAP header which is also signed by the signature, this becomes a demonstration of enveloped signature.

I am using Apache Santuario library for signing. Following is the code segment I used. I have shared the complete sample here to to be downloaded.

public static void main(String unused[]) throws Exception {

        String keystoreType = "JKS";
        String keystoreFile = "src/main/resources/PushpalankaKeystore.jks";
        String keystorePass = "pushpalanka";
        String privateKeyAlias = "pushpalanka";
        String privateKeyPass = "pushpalanka";
        String certificateAlias = "pushpalanka";
        File signatureFile = new File("src/main/resources/signature.xml");
        Element element = null;
        String BaseURI = signatureFile.toURI().toURL().toString();
        //SOAP envelope to be signed
        File attachmentFile = new File("src/main/resources/sample.xml");

        //get the private key used to sign, from the keystore
        KeyStore ks = KeyStore.getInstance(keystoreType);
        FileInputStream fis = new FileInputStream(keystoreFile);
        ks.load(fis, keystorePass.toCharArray());
        PrivateKey privateKey =

                (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());
        //create basic structure of signature
        javax.xml.parsers.DocumentBuilderFactory dbf =
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(attachmentFile);
        XMLSignature sig =
                new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1);

        //optional, but better
        element = doc.getDocumentElement();

            Transforms transforms = new Transforms(doc);
            //Sign the content of SOAP Envelope
            sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);

            //Adding the attachment to be signed
            sig.addDocument("../resources/attachment.xml", transforms, Constants.ALGO_ID_DIGEST_SHA1);


        //Signing procedure
            X509Certificate cert =
                    (X509Certificate) ks.getCertificate(certificateAlias);

        //write signature to file
        FileOutputStream f = new FileOutputStream(signatureFile);
        XMLUtils.outputDOMc14nWithComments(doc, f);

At first it reads in the private key which is to be used in signing. To create a key pair for your own, this post  will be helpful. Then it has created the signature and added the SOAP message and the attachment as the documents to be signed. Finally it performs signing  and write the signed document to a file.

The signed SOAP message looks as follows.

<soap:Envelope xmlns:dsig="" xmlns:pj=""
        <pj:MessageHeader pj:version="1.0" soap:mustUnderstand="1">
                <pj:PartyId pj:type="ABCDE">FUN</pj:PartyId>
                <pj:PartyId pj:type="ABCDE">PARTY</pj:PartyId>
            <pj:ConversationId>FUN PARTY FUN 59c64t0087fg3kfs000003n9</pj:ConversationId>
                <pj:MessageId>FUN 59c64t0087fg3kfs000003n9</pj:MessageId>
        <pj:Via pj:id="59c64t0087fg3ki6000003na" pj:syncReply="False" pj:version="1.0"
                soap:actor="" soap:mustUnderstand="1">
        <ds:Signature xmlns:ds="">
                <ds:SignatureMethod Algorithm=""></ds:SignatureMethod>
                <ds:Reference URI="">
                    <ds:DigestMethod Algorithm=""></ds:DigestMethod>
                <ds:Reference URI="../resources/attachment.xml">
                        <ds:Transform Algorithm=""></ds:Transform>
                    <ds:DigestMethod Algorithm=""></ds:DigestMethod>
            <ds:SignatureValue>d0hBQLIvZ4fwUZlrsDLDZojvwK2DVaznrvSoA/JTjnS7XZ5oMplN9  THX4xzZap3+WhXwI2xMr3GKO................x7u+PQz1UepcbKY3BsO8jB3dxWN6r+F4qTyWa+xwOFxqLj546WX35f8zT4GLdiJI5oiYeo1YPLFFqTrwg==
   <ds:X509Certificate>                MIIDjTCCAnWgAwIBAgIEeotzFjANBgkqhkiG9w0BAQsFADB3MQswCQYDVQQGEwJMSzEQMA4GA1UE...............qXfD/eY+XeIDyMQocRqTpcJIm8OneZ8vbMNQrxsRInxq+DsG+C92b
        <pr:GetPriceResponse xmlns:pr="">

In a next post we will see how to verify this signature, so that we can guarantee signed documents are not changed (in other words guarantee that the integrity of the content is preserved) .


Wednesday, February 19, 2014

Latest ESB Performance Round

The results of latest round of ESB performance study is out now, which has been conducted by WSO2, comparing performance of 4 open source ESBs.  This is an open and repeatable performance study, where the used EC2 AMI is published as a public AMI that contains all the configured ESBs and execution logs along with system configurations.

Following graph summarizes the results where we can clearly see WSO2 ESB leading in performance, outperforming other ESBs.

Understanding ESB Performance

We can refer this blogpost(Understanding ESB Performnce) to understand more on the bench-marking ESBs and what to read from the results.

Is It Only Performance?

This graph is just about performance which is a critical aspect of an ESB. But there are more aspects to be considered on ESBs. If we want to know what added values are there in WSO2 ESB which has been evolving over 7 years, this blogpost(WSO2 ESB: Why Does It Matter) will be of use.

Thursday, February 06, 2014

WSO2 DSS - Batch Insert Sample (end to end)

WSO2 DSS wraps Data Services Layer and provides us with a simple GUI to define a Data Service with zero Java code. With this, a change to the data source is just a simple click away and no other party needs to be aware of this.

With this sample demonstration, we will see how to do a batch insert to a table. Batch insert is useful when you want to insert data in sequential manner. This also means that if at least one of the insertion query fails all the other queries ran so far in the batch will be rolled back as well. If one insertion in the batch fails means whole batch is failed.

This can be used if you are running the same query to insert data many times. With batch insert all the data will be sent in one call. So this reduce the number calls you have to call, to get the data inserted. 

This comes with one condition that,
The query should not be producing results back. (We will only be notified whether the query was successful or not.)

WSO2 Data Services Server - (current latest 3.1.1)

If we already have a data service running which is not sending back a result set , then it's just a matters of adding following property in service declaration.


Anyway I will be demonstrating the creation of the service from the scratch.

1. Create a service as follows going through the wizard,

2. Create the data source

3. Create the query - (This is an insert query. Also note the input mapping we have add as relevant to the query. To know more about input mapping and using validation refer the documentation.)

4. Create the operation - Select the query to be executed once the operation is called. By enabling return request status, we will be notified whether the operation was a success or not.

5. Try it! - When we list the services we will see this new service now. In the right we will have an option to try it.

Here we can see the option to try the service giving the input parameters. Here I have tried it two insertions in a batch.
Now if we go to XML view of the service it will be similar to following, which is saved in server as a .dbs file.

<data enableBatchRequests="true" name="BatchInsertSample">
   <config id="json">
      <property name="driverClassName">com.mysql.jdbc.Driver</property>
      <property name="url">jdbc:mysql://localhost:3306/json_array</property>
      <property name="username">root</property>
      <property name="password">root</property>
      <property name="minIdle">1</property>
      <property name="maxActive">10</property>
      <property name="validationQuery">SELECT 1</property>
   <query id="addFlightQuery" useConfig="json">
      <sql>insert into flights (flight_no, number_of_cases, created_by, description, trips) values (:flight_no,:number_of_cases,:created_by,:description,:trips)</sql>
      <param name="flight_no" ordinal="1" sqlType="BIGINT"/>
      <param name="number_of_cases" ordinal="2" sqlType="BIGINT"/>
      <param name="created_by" ordinal="3" sqlType="STRING"/>
      <param name="description" ordinal="4" sqlType="STRING"/>
      <param name="trips" ordinal="5" sqlType="BIGINT"/>
   <operation name="addFlight" returnRequestStatus="true">
      <call-query href="addFlightQuery">
         <with-param name="flight_no" query-param="flight_no"/>
         <with-param name="number_of_cases" query-param="number_of_cases"/>
         <with-param name="created_by" query-param="created_by"/>
         <with-param name="description" query-param="description"/>
         <with-param name="trips" query-param="trips"/>

If we hit on the service name in the list of services, we will be directed to Service Dashboard where we can see several other options for the service. It provides the option to generate an Axis2 client for the service. Once we get the client then it's a matter of calling the methods in the stub as follows.

private static BatchRequestSampleOldStub.AddFlight_type0 createFlight(int cases, String creator, String description, int trips) {

        BatchRequestSampleOldStub.AddFlight_type0 val = new BatchRequestSampleOldStub.AddFlight_type0();
        printFlightInfo(cases, creator, description, trips);
        return val;

    public static void main(String[] args) throws Exception {
        String epr = "http://localhost:9763" + "/services/BatchInsertSample";
        BatchRequestSampleOldStub stub = new BatchRequestSampleOldStub(epr);
        BatchRequestSampleOldStub.AddFlight_batch_req vals1 = new BatchRequestSampleOldStub.AddFlight_batch_req();

        vals1.addAddFlight(createFlight(1, "Pushpalanka", "test", 2));
        vals1.addAddFlight(createFlight(2, "Jayawardhana", "test", 2));
        vals1.addAddFlight(createFlight(3, "", "test", 2));
        try {
            System.out.println("Executing Add Flights..");
        } catch (Exception e) {
            System.out.println("Error in Add Flights!");

Complete client code can be found here.



Thursday, January 30, 2014

Invoking APIs using a Web App with OAuth2 and use of JWT - WSO2 API Manager

In this post I am to share my experience and understandings using WSO2 API Manager(API-M) for a very common and useful scenario in the industry. 

In brief following is the flow.

An API is exposed for app developers to be used under the control of API Manager (which adds access control for the API). Then app developers make their apps consuming those APIs. After development and testing is completed they make it available for end users at App store. The end users can then get registered in the store and use the apps with own credentials. The app will provide the desired services calling the APIs it has subscribed to.

The above scenario is well demonstrated in WSO2 API-M with the pizza shack example explained in the documentation at [1].

For clarity I will be including the steps in brief. For detailed steps we can refer documentation at [1]. 

API Developer Role

  • We deploy the back-end services related to 'pizza ordering' in WSO2-Application server or any other desired application server. (Download the code from API-M samples svn, build using Maven3 and deploy it in WSO2 AS. If we check the WADL, we can check the resources it exposes. Note the endpoint URL.)

  • Then we publishes these services as APIs in WSO2 API-M Publisher, so that they will be available in API-M Store (Login to API-M Publisher, in default pack https://localhost:9443/publisher and publish the APIs as guided in the sample doc. We should make sure the production endpoint URL  matches with what we observed in the first step). 

App Developer Role

  • Now here comes an App developer who wish to develop an App to order Pizza. He/she can register this App in store and get subscribed to these APIs that are required for development of application. So this APP developer will be consuming the services exposed by the APIs published by the previous developer. The code for the pizza ordering sample web app can be downloaded from svn as well.

  • At subscription he/she gets consumer secret and consumer key which are then used to request OAuth tokens to access the APIs (In this example we use user name and password which is required in grant type 'password'. There are several other possible grant types as well, if we don't want to send password).

Get the consumer key and secret from 'My Subscriptions'.


  • Developer embeds the consumer key and consumer secret into the Pizza ordering application (In most of the cases in web.xml).

At this point we can check how the token works with a simple curl command as follows. Provide the access token taken from above UI.
curl -k -H "Authorization: Bearer <access_token>" https://localhost:8245/pizzashack/menu/1.0.0

 which will return the menu details for pizza orering as follows,

[{"price":"13.99","icon":"/images/6.png","description":"Grilled white chicken, hickory-smoked bacon and fresh sliced onions in barbeque sauce","name":"BBQ Chicken Bacon"},{"price":"24.99","icon":"......................:"/images/5.png","description":"Rich and creamy blend of spinach and garlic Parmesan with Alfredo sauce","name":"Spinach Alfredo"},{"price":"15.99","icon":"/images/4.png","description":"Six cheese blend of mozzarella, Parmesan, Romano, Asiago and Fontina","name":"Tuscan Six Cheese"}]

Since we have already seen the access token we can use it here. But when an end user comes and tries to order pizzas he/she is not seen these. Also this token is related with USER_TYPE: APPLICATION which has more privileges than an end user, so we can't anyway let the user use it. So what is happening underneath is generating a separate token for end users, using the embedded consumer key/secret and end user entered credentials(if password grant type is used) which will be related with USER_TYPE: APPLICATION_USER.

End User

So here comes the end user who get registered in the App Store.
Then end users can use the application to order pizzas online, entering their credentials in the application at http://localhost/pizzashack.

The API-M sitting in the middle act as the Authorization server in the scenario, managing the usage of the exposed APIs.

So where does the JWT assertion comes into play?

JWT assertion is a format used to send the details of the end user who invoked the API. Just as a SAML assertion would carry user claims JWT also carries user claims in JSON notation. We can find more details on this at [2]. This is used to pass those details to the back-end service which might require them for monitoring or some other purpose. The default JWT token will be as follows.



Friday, January 17, 2014

How to send an HTML email in Java (Using Google SMTP Server)

In most of the business services sometimes there comes requirements to send notifications to users or administrators via email.

For example :
  • Confirming a user registration
  • Password reset via emails
Following code segments can be used to send these emails using Google SMTP server. Here I am sharing two ways to do it. 
  1. Using javax.mail.jar directly
  2. Using Apache commons email jar which wraps javax.mail 

Using javax.mail

try {
            Properties props = new Properties();
            props.put("", "");
            props.put("mail.smtp.auth", "true");
            props.put("mail.debug", "false");
            props.put("mail.smtp.ssl.enable", "true");

            Session session = Session.getInstance(props, new EmailAuth());
            Message msg = new MimeMessage(session);

            InternetAddress from = new InternetAddress("sendersEmailAddress", "Sender's name");

            InternetAddress toAddress = new InternetAddress("Receiver's email");

            msg.setRecipient(Message.RecipientType.TO, toAddress);

            msg.setContent(msg.setContent("<html>\n" +
                    "<body>\n" +
                    "\n" +
                    "<a href=\"\">\n" +
                    "This is a link</a>\n" +
                    "\n" +
                    "</body>\n" +
                    "</html>", "text/html");, "text/html");
        } catch (UnsupportedEncodingException ex) {

        } catch (MessagingException ex) {

    static class EmailAuth extends Authenticator {

        protected PasswordAuthentication getPasswordAuthentication() {

            return new PasswordAuthentication("sendersEmailAddress", "password");


Using Apache commons e-mail

        HtmlEmail email = new HtmlEmail();
        email.setAuthenticator(new DefaultAuthenticator("sendersEmailAddress", "password"));
        email.setFrom("Senders' email");
        email.setSubject("TestMail- Alternative message");
        email.setHtmlMsg("<html>\n" +
                "<body>\n" +
                "\n" +
                "<a href=\"\">\n" +
                "This is a link</a>\n" +
                "\n" +
                "</body>\n" +
        // set the alternative message
        email.setTextMsg("This is a link:");
Here with setTextMsg method we can set a plain text message to be shown at receiver's end if receiver is not supporting HTML content in emails.

If the gmail account used to send the email is 2-Step verification enabled and you used your usual password to send the email in code, you will get a similar error to the following.

javax.mail.AuthenticationFailedException: 534-5.7.9 Application-specific password required. Learn more at 534 5.7.9

The solution is to go to Account>Security>App passwords>Settings and generate a password for the app we are to run. 

[1] -
[2] -