Apply OAuth2.0 base security for Rest endpoint with WSO2ESB 4.6.0 and WSO2IS 4.1.1 alpha

05 Apr

I think this would be good example for applying the security for the simple rest endpoint. Lets think we already have some rest endpoint without security but we need to expose this with the OAuth2.0 base security.

you can achieve this task with the following steps.

1. Create the custom handler to validate the Bearer token.
2. Create API element in the ESB and pointing the rest endpoint that you have
3. Include created handler to the created API element.
4. Go to IS and create the OAuth2.0 application and get the Access token form IS
5. Invoke the API with the valid access token.

Functional Scenario

Rest endpoint with security

1. Creating custom handler (Download the mvn project here)
You need to extends AbstractHandler and implements ManagedLifecycle as follows. as well I’m getting some parameters from the axis2.xml

package org.wso2.handler;

 * Created with IntelliJ IDEA.
 * User: dinuka
 * Date: 4/4/13
 * Time: 3:46 PM
 * To change this template use File | Settings | File Templates.
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.axis2.transport.http.HttpTransportProperties;
import org.apache.http.HttpHeaders;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub;
import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO;
import org.apache.synapse.ManagedLifecycle;
import org.apache.synapse.MessageContext;
import org.apache.synapse.core.SynapseEnvironment;

import java.util.Map;

public class SimpleOauthHandler extends AbstractHandler implements ManagedLifecycle {

    private String securityHeader = HttpHeaders.AUTHORIZATION;
    private String consumerKeyHeaderSegment = "Bearer";
    private String oauthHeaderSplitter = ",";
    private String consumerKeySegmentDelimiter = " ";
    private String oauth2TokenValidationService = "oauth2TokenValidationService";
    private String identityServerUserName = "identityServerUserName";
    private String identityServerPw = "identityServerPw";

    public boolean handleRequest(MessageContext messageContext) {
            ConfigurationContext configCtx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
            //Read parameters from axis2.xml
            String identityServerUrl = messageContext.getConfiguration().getAxisConfiguration().getParameter(oauth2TokenValidationService).getValue().toString();
            String username = messageContext.getConfiguration().getAxisConfiguration().getParameter(identityServerUserName).getValue().toString();
            String password = messageContext.getConfiguration().getAxisConfiguration().getParameter(identityServerPw).getValue().toString();

            OAuth2TokenValidationServiceStub stub = new OAuth2TokenValidationServiceStub(configCtx,identityServerUrl);
            ServiceClient client = stub._getServiceClient();
            Options options = client.getOptions();
            HttpTransportProperties.Authenticator authenticator = new HttpTransportProperties.Authenticator();

            options.setProperty(HTTPConstants.AUTHENTICATE, authenticator);
            OAuth2TokenValidationRequestDTO dto = new OAuth2TokenValidationRequestDTO();
            Map headers = (Map) ((Axis2MessageContext) messageContext).getAxis2MessageContext().
            String apiKey = null;
            if (headers != null) {
                apiKey = extractCustomerKeyFromAuthHeader(headers);
            //validate passed apiKey(token)
                return true;
                return false;
        }catch(Exception e){
            return false;

    public String extractCustomerKeyFromAuthHeader(Map headersMap) {

        //From 1.0.7 version of this component onwards remove the OAuth authorization header from
        // the message is configurable. So we dont need to remove headers at this point.
        String authHeader = (String) headersMap.get(securityHeader);
        if (authHeader == null) {
            return null;

        if (authHeader.startsWith("OAuth ") || authHeader.startsWith("oauth ")) {
            authHeader = authHeader.substring(authHeader.indexOf("o"));

        String[] headers = authHeader.split(oauthHeaderSplitter);
        if (headers != null) {
            for (int i = 0; i < headers.length; i++) {
                String[] elements = headers[i].split(consumerKeySegmentDelimiter);
                if (elements != null && elements.length > 1) {
                    int j = 0;
                    boolean isConsumerKeyHeaderAvailable = false;
                    for (String element : elements) {
                        if (!"".equals(element.trim())) {
                            if (consumerKeyHeaderSegment.equals(elements[j].trim())) {
                                isConsumerKeyHeaderAvailable = true;
                            } else if (isConsumerKeyHeaderAvailable) {
                                return removeLeadingAndTrailing(elements[j].trim());
        return null;

    private String removeLeadingAndTrailing(String base) {
        String result = base;

        if (base.startsWith("\"") || base.endsWith("\"")) {
            result = base.replace("\"", "");
        return result.trim();

    public boolean handleResponse(MessageContext messageContext) {
      return true;

    public void init(SynapseEnvironment synapseEnvironment) {
        //To change body of implemented methods use File | Settings | File Templates.

    public void destroy() {
        //To change body of implemented methods use File | Settings | File Templates.

2. Now I take rest unsecured endpoint as ““(You can use your own endpoint)
Lets look at how to configure the WSO2 ESB with this endpoint.

Start the ESB 4.6.0 and Sign in as admin.
Then go to Source View.

Insert following xml configuration in to the source view to create the API element name as TestGoogle

  <api name="TestGoogle" context="/search">
      <resource methods="GET">
            <log level="custom">
               <property name="Test" value="Test"/>
                  <address uri=""/>
         <handler class="org.wso2.handler.SimpleOauthHandler"/>


3. We need to add the created custom handler.jar in to $ESB_HOME/repository/components/libs and go to the $ESB_HOME/repository/conf/axis2/axis2.xml and put the following parameters.

    <!-- OAuth2 Token Validation Service -->
    <parameter name="oauth2TokenValidationService">https://localhost:9444/services/OAuth2TokenValidationService</parameter>
    <!-- Server credentials -->
    <parameter name="identityServerUserName">admin</parameter>
    <parameter name="identityServerPw">admin</parameter>

restart the ESB.

Again go to source view and place the following xml to engage the custom handler in to the API element

         <handler class="org.wso2.handler.SimpleOauthHandler"/>

Total configuration looks like this

  <api name="TestGoogle" context="/search">
      <resource methods="GET">
            <log level="custom">
               <property name="Test" value="Test"/>
                  <address uri=""/>
         <handler class="org.wso2.handler.SimpleOauthHandler"/>

4. Start the WSO2 Identity server and create the Oauth2.0 Application


Request the access token from IS you need to pass the ClientID and Client Secret with the curl request.

curl -v -X POST –user <strong>R2CNjiq672f6xXQabAfWbYby2nca</strong>:<strong>QhEQi9eJv8BmSinPBnWscCFFDgsa</strong> -H "Content-Type: application/x-www-form-urlencoded;charset=UTF-8" -k -d "grant_type=password&username=admin&password=admin" https://localhost:9444/oauth2endpoints/token

Then you will receive the access token

5. Now you can invoke the API with the received access token

curl -v -X GET -H “Authorization: Bearer ca1799fc84986bd87c120ba499838a7”


Tags: , ,

4 responses to “Apply OAuth2.0 base security for Rest endpoint with WSO2ESB 4.6.0 and WSO2IS 4.1.1 alpha

  1. Mike Stuart

    August 15, 2013 at 2:53 am

    I downloaded the maven project, but can’t find all the dependencies. Are there any special repositories (from WSO2?) that need to be specified? Also, I’ll go to the WSO2 docs for the info, but at least a note on how to deploy the handler after it is build would be nice. But very helpful and well written, thanks.

    • Bhathiya

      February 3, 2014 at 12:25 pm

      pom.xml should be changed as follows.

      <?xml version="1.0" encoding="UTF-8"?>
      <project xmlns=";

      <name>WSO2 internal Repository</name>


  2. faisal

    June 12, 2014 at 6:41 am

    I have requirement bit different i get normal header request with username&password need to validate with wso2 esb user-store like username-token done.But username-token has its own message format where as my client is not sending me in that format how would i change header before the proxy.
    please refer this

  3. Mac

    October 31, 2014 at 3:52 pm

    I have followed all the steps that are depicted in this tutorial, but in step 5, I can access the API with any token or an empty token. The API should only be accessed with the access token that is provided in step 4.
    Is it missing something to validate the token?


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 43 other followers

%d bloggers like this: