Access Token-Based Authentication and Authorization using XACML

  • By Dushan Abeyruwan
  • 30 Apr, 2014
Archived Content
This article is provided for historical perspective only, and may not reflect current conditions. Please refer to relevant product page for more up-to-date product information and resources.

Table of contents

  • Introduction
  • Fundamentals of XACML
  • Scenario
    • Defining the user story
    • Permission tree
    • Try it test for fine-grained authorization
  • Setup scenario
    • Setting up WSO2 Identity Server (IS)
      • Identity server getting the OAuth token
    • Setting up WSO2 ESB as PEP
      • WSO2 ESB additional settings
  • Running the scenario using SOAP UI
  • Appendix A
    • REST API
  • Appendix B
    • XACML definition
  • Appendix C
    • REST API handler
  • References

Introduction

In terms of services invocation for cases of REST, when a client attempts to access a privileged resource, credentials must be provided in an authorization header or the client will be refused access.

In WSO2 ESB, when you take into consideration RESTful integration the REST APIs need to be secured. It can be made available via HTTPS and the security handler will validate the credentials. The ESB doesn’t include REST security handlers by default. Both authorization and authentication are key aspects of identity management in enterprise applications. They both play equally important roles when securing RESTfully exposed APIs.

The use-case that is going to be discussed integrates components such as authentication handling by exchanging access tokens with identity federation and user authorization. This means that the customer or consumer is allowed to perform that particular operation by integrating XACML-based fine grain authorization technologies.

For more information on the implementation of XACML watch our webinar on

Fundamentals of XACML

One key aspect of PBAC solutions based on XACML is the reference architecture that defines key components involved in access management according to their responsibility. The following are the logical components present in the WSO2 setup;

  • Policy Administration Point (PAP) - WSO2 Identity Server - this is where XACML authorization policies are governed
  • Policy Enforcement Point (PEP) - WSO2 ESB - this is where the users requests to services are intercepted and the access is allowed or denied according to the decision given by the PDP
  • Policy Decision Point (PDP) - WSO2 Identity Server - this is where an authorization decision is taken by evaluating the XACML authorization request sent by PEP, against a matching XACML policy found in PAP
  • Policy Information Point (PIP) - User store of WSO2 Identity Server - this is where required attributes of the user who is trying to access the resource will be read by the PDP in order to make the authorization decision

Scenario

Figure 1

Figure 1 illustrates the user authentication and authorization flow. This is explained in detail in the step-by-step description below.

  1. The user registers with the identity server and provides the Client Id and Client Secret
  2. Figure 2

  3. The client implements the skeleton to communicate with the Identity server and retrieves the access token, which is similar to the given curl command
  4. curl -v -k -X POST --user

    mGwx39CukOfOZ9uoZohMXKFv0cMa:aT7nS_D68F96mzfwpmSwO57lAWQa -H

    "Content-Type: application/x-www-form-urlencoded;charset=UTF-8" -d

    'grant_type=password&username=dushan&password=admin'

    upload completely sent off: 50 out of 50 bytes

    < HTTP/1.1 200 OK

    < Cache-Control: no-store

    < Date: Thu, 27 Mar 2014 12:11:57 GMT

    < Pragma: no-cache

    < Content-Type: application/json

    < Content-Length: 140

    * Server WSO2 Carbon Server is not deny listed

    < Server: WSO2 Carbon Server

    <

    * Connection #0 to host localhost left intact

    {"token_type":"bearer","expires_in":3600,"refresh_token":"3510df18f339a32511b93e92a12a8e","access_token":"a3b0d1fe2d2e3b78402e2c19dea7dcf3"}

  5. The client invokes the REST API and embedding access token as the Authorization Header
  6. The ESB REST API receives the invocation request; the request is delegated to the REST Security handler (org.wso2.handler.SimpleOauthHandler); see Appendix A for handler implementation
  7. The Security Handler authorizes the request by validating the access token. (up to this point if the user is allowed to proceed then it means that the user is at a proper authentication level).
  8. Then request will be dispatched to the required REST API resource and before it calls any BE the user request will be authorized at the mediation flow.
  9. For authorization, it uses the entitlement meditator (see Appendix A) who communicates with the identity server and passes information, such as that in Appendix B, for
    1. Resource; context the path which the user is supposed to retrieve the value from
    2. Subject; the username will be bound by invoking claim service for the given access token which evaluates the user role
    3. Action; defines the HTTP verb which the client tries to perform such as GET POST DELETE PUT for /pizzashop-rs_1.0/services/menu/order (See Appendix)
  10. If the user is granted permission then the remaining mediation logic will be executed and BE services will be invoked
  11. Else the user will be directed to any fault or respective un-authorization request handler

The permission tree

Role User CAN_POST CAN_EDIT CAN_GET
Foo YES NO YES
Bar YES YES NO
Zoo NO NO YES

Figure 3

Figure 4

‘Try It’ Test for Fine Grained Authorization

Testing Foo user Authorization levels

XACML definition

  • If any user request tries to access /pizzashop-rs_1.0/services/menu/order (resource) and needs to invoke POST operation they should have the CAN_POST role assigned.
  •   
     
          
             
                
                   
                      /pizzashop-rs_1.0/services/menu/order
    
    
              
                
                CAN_POST
          ……….
    
  • If any user tries to access /pizzashop-rs_1.0/services/menu/order (resource) and tries the GET invocation they should have CAN_GET role assigned.
  • If any user tries to access /pizzashop-rs_1.0/services/menu/order (resource) and tries the PUT (edit) invocation they should have CAN_EDIT role assigned.

Figure 5

Figure 6

Figure 7

Setting up WSO2 Identity Server (IS)

  1. The identity server plays the roles of PAP, PDP and PIP in our solution as mentioned above. Download Identity Server, change its Ports.Offset to 1 in carbon.xml found in [IS_HOME]/repository/conf and run the server.
  2. Login to management console (https://localhost:9444/carbon/) as admin.
  3. Now, Use the XACML definition given in Appendix B and upload policy into IS through Entitlement->Administration->Import New Entitlement Policy as shown below. Once imported, 'enable' the policy from the icon in front of the policy name.

Getting the OAuth token

  • Start WSO2 Identity Server and log into the management console.
  • Click Manage -> OAuth and create an OAuth application.
  • Note the access token URL and embed it in a cURL request to get the token. For example, use the following command and replace and with the actual values:
  • Figure 8

    Setting up WSO2 ESB as PEP

    • Download and start the ESB after following “Additional Setting section “ with default port offsetting
    • Use the Appendix A REST API synapse configuration.
    • Use the Appendix D section to download all the materials related to this discussion including the REST API handler and other relevant configurations.
    • You will notice that in REST API we are using an entitlement mediator, which is the key entry point in order to communicate with the identity server for XACML based authorization. If the identity server permits the user the section will execute and the remaining mediation logic will continue. If access is denied the phase will be executed.
    • Please note that “xacml_resource_prefix” enables you to define the resource element for the XACML request via the entitlement mediator.

      Once the access token is retrieved the REST API handler itself communicates through the identity server and obtains the username of the request entity and sets it in the message context

      • See Appendix C (Custom REST API handler)
      
    String user = stub.validate(dto).getAuthorizedUser();
    				System.out.println();
    				user = user.substring(0, user.indexOf('@'));
    				System.out.println(username);
    				org.apache.axis2.context.MessageContext msgContext;
    				Axis2MessageContext axis2Msgcontext = null;
    				axis2Msgcontext = (Axis2MessageContext) messageContext;
    				msgContext = axis2Msgcontext.getAxis2MessageContext();
    				msgContext.setProperty("username", user);
    

    This will be set as the Subject in the XACML request via the entitlement mediator.

    Additional settings of WSO2 ESB

    Open /repository/conf/axis2/axis2.xml and add the following parameters:

      
    axis2.xml
    
    https://localhost:9444/services/OAuth2TokenValidationService
    https://localhost:9444/services/OAuth2Service
    
    admin
    admin
    
    

    Running the scenario using SOAP UI

    • Retrieve access token by passing user credentials [Figure 9]
    • Figure 9

    • User Foo does a POST request to insert the Pizza order. The request is granted since the access token and and user permission are both valid. [Figure 10]
    • Figure 10

    • User Foo does a GET request to insert the Pizza order. It is created and the request is granted since the access token and user permission are valid [Figure 11]
    • Figure 11

    • User Foo does a PUT request to edit the Pizza order. The request is denied because although the access token is granted the user doesn’t have a proper authorization level. [Figure 12]
    • Figure 12

    Read how BDigital used pre-integrated WSO2 middleware products to mediate services across the cloud and Internet of Things in our case study on

    Appendix A

    REST API

      
    <api name="pizzashop" context="/pizzashop">
          <resource methods="POST GET DELETE PUT" uri-template="/api/order/{orderId}">
             <inSequence>
                <log>
                   <property name="Message Flow" value="Pizza Order API - IN"/>
                </log>
                <property name="xacml_use_rest" value="true" scope="axis2"/>
                <property name="xacml_resource_prefix"
                          value="/pizzashop-rs_1.0/services/menu/order"
                          scope="axis2"/>
                <property name="xacml_resource_prefix_only" value="true" scope="axis2"/>
                <entitlementService remoteServiceUrl="https://localhost:9444/services"
                                    remoteServiceUserName="admin"
                                    remoteServicePassword="enc:kuv2MubUUveMyv6GeHrXr9il59ajJIqUI4eoYHcgGKf/BBFOWn96NTjJQI+wYbWjKW6r79S7L7ZzgYeWx7DlGbff5X3pBN2Gh9yV0BHP1E93QtFqR7uTWi141Tr7V7ZwScwNqJbiNoV+vyLbsqKJE7T3nP8Ih9Y6omygbcLcHzg="
                                    callbackClass="org.wso2.carbon.identity.entitlement.mediator.callback.UTEntitlementCallbackHandler"
                                    client="basicAuth">
                   <onReject>
                      <log>
                         <property name="Message Flow" value="[email protected]"/>
                      </log>
                      <property name="HTTP_SC" value="401" scope="axis2"/>
                      <payloadFactory media-type="xml">
                         <format>
                            <OAtherizationResponse xmlns="">Not Authorized </OAtherizationResponse>
                         </format>
                         <args/>
                      </payloadFactory>
                      <respond/>
                   </onReject>
                   <onAccept>
                      <log>
                         <property name="Message Flow" value="[email protected]"/>
                      </log>
                      <switch source="$axis2:HTTP_METHOD">
                         <case regex="GET">
                            <log level="custom">
                               <property name="Message Flow" value="--- Order GET ---"/>
                            </log>
                            <send>
                               <endpoint>
                                  <http method="GET"
                                        uri-template="https://localhost:9765/pizzashop-rs_1.0/services/menu/order/{uri.var.orderId}"/>
                               </endpoint>
                            </send>
                         </case>
                         <case regex="PUT">
                            <log level="custom">
                               <property name="Message Flow" value="--- Order PUT ---"/>
                            </log>
                            <send>
                               <endpoint>
                                  <http method="PUT"
                                        uri-template="https://localhost:9765/pizzashop-rs_1.0/services/menu/order/{uri.var.orderId}"/>
                               </endpoint>
                            </send>
                         </case>
                         <case regex="DELETE">
                            <log level="custom">
                               <property name="Message Flow" value="--- Order DELETE ---"/>
                            </log>
                            <send>
                               <endpoint>
                                  <http method="DELETE"
                                        uri-template="https://localhost:9765/pizzashop-rs_1.0/services/menu/order/{uri.var.orderId}"/>
                               </endpoint>
                            </send>
                         </case>
                      </switch>
                   </onAccept>
                   <obligations/>
                   <advice/>
                </entitlementService>
             </inSequence>
             <outSequence>
                <send/>
             </outSequence>
          </resource>
          <resource methods="POST" uri-template="/api/order*">
             <inSequence>
                <log>
                   <property name="Message Flow" value="Pizza Order API - IN"/>
                </log>
                <property name="xacml_use_rest" value="true" scope="axis2"/>
                <property name="xacml_resource_prefix"
                          value="/pizzashop-rs_1.0/services/menu/order"
                          scope="axis2"/>
                <property name="xacml_resource_prefix_only" value="true" scope="axis2"/>
                <log>
                   <property name="Message Flow" value="IN"/>
                </log>
                <entitlementService remoteServiceUrl="https://localhost:9444/services"
                                    remoteServiceUserName="admin"
                                    remoteServicePassword="enc:kuv2MubUUveMyv6GeHrXr9il59ajJIqUI4eoYHcgGKf/BBFOWn96NTjJQI+wYbWjKW6r79S7L7ZzgYeWx7DlGbff5X3pBN2Gh9yV0BHP1E93QtFqR7uTWi141Tr7V7ZwScwNqJbiNoV+vyLbsqKJE7T3nP8Ih9Y6omygbcLcHzg="
                                    callbackClass="org.wso2.carbon.identity.entitlement.mediator.callback.UTEntitlementCallbackHandler"
                                    client="basicAuth">
                   <onReject>
                      <property name="HTTP_SC" value="401" scope="axis2"/>
                      <log>
                         <property name="Message Flow" value="[email protected]"/>
                      </log>
                      <payloadFactory media-type="xml">
                         <format>
                            <OAtherizationResponse xmlns="">Not Authorized </OAtherizationResponse>
                         </format>
                         <args/>
                      </payloadFactory>
                      <respond/>
                   </onReject>
                   <onAccept>
                      <log>
                         <property name="Message Flow" value="[email protected]"/>
                      </log>
                      <send>
                         <endpoint>
                            <http method="post"
                                  uri-template="https://localhost:9765/pizzashop-rs_1.0/services/menu/order"/>
                         </endpoint>
                      </send>
                   </onAccept>
                   <obligations/>
                   <advice/>
                </entitlementService>
             </inSequence>
             <outSequence>
                <send/>
             </outSequence>
          </resource>
          <handlers>
             <handler class="org.wso2.handler.SimpleOauthHandler"/>
          </handlers>
       </api>
    

    Appendix B

    XACML definition

      
    <Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17"  PolicyId="PizzaOrderOAuth" RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable" Version="1.0">
       <Target>
          <AnyOf>
             <AllOf>
                <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-regexp-match">
                   <AttributeValue DataType="https://www.w3.org/2001/XMLSchema#string">/pizzashop-rs_1.0/services/menu/order</AttributeValue>
                   <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" DataType="https://www.w3.org/2001/XMLSchema#string" MustBePresent="true"></AttributeDesignator>
                </Match>
             </AllOf>
          </AnyOf>
       </Target>
       <Rule Effect="Permit" RuleId="Rule-1">
          <Target>
             <AnyOf>
                <AllOf>
                   <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-regexp-match">
                      <AttributeValue DataType="https://www.w3.org/2001/XMLSchema#string">/pizzashop-rs_1.0/services/menu/order</AttributeValue>
                      <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" DataType="https://www.w3.org/2001/XMLSchema#string" MustBePresent="true"></AttributeDesignator>
                   </Match>
                </AllOf>
             </AnyOf>
             <AnyOf>
                <AllOf>
                   <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
                      <AttributeValue DataType="https://www.w3.org/2001/XMLSchema#string">POST</AttributeValue>
                      <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action" DataType="https://www.w3.org/2001/XMLSchema#string" MustBePresent="true"></AttributeDesignator>
                   </Match>
                </AllOf>
             </AnyOf>
          </Target>
          <Condition>
             <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:any-of">
                <Function FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-equal"></Function>
                <AttributeValue DataType="https://www.w3.org/2001/XMLSchema#string">CAN_POST</AttributeValue>
                <AttributeDesignator AttributeId="https://wso2.org/claims/role" Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" DataType="https://www.w3.org/2001/XMLSchema#string" MustBePresent="true"></AttributeDesignator>
             </Apply>
          </Condition>
       </Rule>
       <Rule Effect="Permit" RuleId="Rule-2">
          <Target>
             <AnyOf>
                <AllOf>
                   <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-regexp-match">
                      <AttributeValue DataType="https://www.w3.org/2001/XMLSchema#string">/pizzashop-rs_1.0/services/menu/order</AttributeValue>
                      <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" DataType="https://www.w3.org/2001/XMLSchema#string" MustBePresent="true"></AttributeDesignator>
                   </Match>
                </AllOf>
             </AnyOf>
             <AnyOf>
                <AllOf>
                   <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
                      <AttributeValue DataType="https://www.w3.org/2001/XMLSchema#string">PUT</AttributeValue>
                      <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action" DataType="https://www.w3.org/2001/XMLSchema#string" MustBePresent="true"></AttributeDesignator>
                   </Match>
                </AllOf>
             </AnyOf>
          </Target>
          <Condition>
             <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:any-of">
                <Function FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-equal"></Function>
                <AttributeValue DataType="https://www.w3.org/2001/XMLSchema#string">CAN_EDIT</AttributeValue>
                <AttributeDesignator AttributeId="https://wso2.org/claims/role" Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" DataType="https://www.w3.org/2001/XMLSchema#string" MustBePresent="true"></AttributeDesignator>
             </Apply>
          </Condition>
       </Rule>
       <Rule Effect="Permit" RuleId="Rule-3">
          <Target>
             <AnyOf>
                <AllOf>
                   <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-regexp-match">
                      <AttributeValue DataType="https://www.w3.org/2001/XMLSchema#string">/pizzashop-rs_1.0/services/menu/order</AttributeValue>
                      <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" DataType="https://www.w3.org/2001/XMLSchema#string" MustBePresent="true"></AttributeDesignator>
                   </Match>
                </AllOf>
             </AnyOf>
             <AnyOf>
                <AllOf>
                   <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
                      <AttributeValue DataType="https://www.w3.org/2001/XMLSchema#string">GET</AttributeValue>
                      <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action" DataType="https://www.w3.org/2001/XMLSchema#string" MustBePresent="true"></AttributeDesignator>
                   </Match>
                </AllOf>
             </AnyOf>
          </Target>
          <Condition>
             <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:any-of">
                <Function FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-equal"></Function>
                <AttributeValue DataType="https://www.w3.org/2001/XMLSchema#string">CAN_GET</AttributeValue>
                <AttributeDesignator AttributeId="https://wso2.org/claims/role" Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" DataType="https://www.w3.org/2001/XMLSchema#string" MustBePresent="true"></AttributeDesignator>
             </Apply>
          </Condition>
       </Rule>
       <Rule Effect="Deny" RuleId="Deny-Rule"></Rule>
    </Policy>        
    

    Appendix C

    REST API handler

      
    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.OAuth2ServiceStub;
    import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub;
    import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO;
    import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_OAuth2AccessToken;
    import org.wso2.carbon.user.api.xsd.Claim;
    import org.apache.synapse.ManagedLifecycle;
    import org.apache.synapse.MessageContext;
    import org.apache.synapse.core.SynapseEnvironment;
    import org.apache.synapse.rest.AbstractHandler;
    
    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";
    	private String oAuth2Service = "oauth2Service";
    
    	@Override
        public boolean handleRequest(MessageContext messageContext) {
            try{
                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);
                
                String oauth2ServiceUrl = messageContext.getConfiguration().getAxisConfiguration().getParameter(oAuth2Service).getValue().toString();
                OAuth2ServiceStub oAuth2ServiceStub = new OAuth2ServiceStub(configCtx,oauth2ServiceUrl);
                
                
                ServiceClient client = stub._getServiceClient();
                Options options = client.getOptions();
                HttpTransportProperties.Authenticator authenticator = new HttpTransportProperties.Authenticator();
                authenticator.setUsername(username);
                authenticator.setPassword(password);
                authenticator.setPreemptiveAuthentication(true);
    
                options.setProperty(HTTPConstants.AUTHENTICATE, authenticator);
                client.setOptions(options);
                OAuth2TokenValidationRequestDTO dto = new OAuth2TokenValidationRequestDTO();
               // dto.set("bearer");
                Map headers = (Map) ((Axis2MessageContext) messageContext).getAxis2MessageContext().
                        getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
                String apiKey = null;
                if (headers != null) {
                    apiKey = extractCustomerKeyFromAuthHeader(headers);
                }
                OAuth2TokenValidationRequestDTO_OAuth2AccessToken accessToken = new OAuth2TokenValidationRequestDTO_OAuth2AccessToken();
                accessToken.setTokenType("bearer");
                accessToken.setIdentifier(apiKey);
                dto.setAccessToken(accessToken);
                //validate passed apiKey(token)
    			if (stub.validate(dto).getValid()) {
    				String user = stub.validate(dto).getAuthorizedUser();
    				System.out.println();
    				user = user.substring(0, user.indexOf('@'));
    				System.out.println(username);
    				org.apache.axis2.context.MessageContext msgContext;
    				Axis2MessageContext axis2Msgcontext = null;
    				axis2Msgcontext = (Axis2MessageContext) messageContext;
    				msgContext = axis2Msgcontext.getAxis2MessageContext();
    				msgContext.setProperty("username", user);
    				return true;
                }else{
                    return false;
                }
            }catch(Exception e){
                e.printStackTrace();
                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());
    							}
    						}
    						j++;
    					}
    				}
    			}
    		}
    		return null;
    	}
    
    	private String removeLeadingAndTrailing(String base) {
    		String result = base;
    
    		if (base.startsWith("\"") || base.endsWith("\"")) {
    			result = base.replace("\"", "");
    		}
    		return result.trim();
    	}
    
    	@Override
    	public boolean handleResponse(MessageContext messageContext) {
    		return true;
    	}
    
    	@Override
    	public void init(SynapseEnvironment synapseEnvironment) {
    		// To change body of implemented methods use File | Settings | File
    		// Templates.
    	}
    
    	@Override
    	public void destroy() {
    		// To change body of implemented methods use File | Settings | File
    		// Templates.
    	}
    }
    
    

    References