Sunday, January 27, 2013

How to write a Custom Authentication Handler for WSO2 API Manger ?


WSO2 API Manager provide OAuth2 bearer token as its default authentication mechanism. But we can extend it to support any of the authentication mechanism other than the bearer token authentication.

This post explains, how we can write a custom authentication handler for WSO2 API Manager. 

Implementation of the default authentication handler used in WSO2 API Manger can be found here. As the same way, we can write our own authentication handler class by extending 'org.apache.synapse.rest.AbstractHandler' class.

In the authentication handler implementation class, we have to implement the 'handleRequest()' and 'handleResponse()' methods. See the sample 'CustomAPIAuthenticationHandler.java' class given bellow. 
 
package org.wso2.carbon.apimgt.gateway.handlers.security;

import org.apache.synapse.MessageContext;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.rest.AbstractHandler;

import java.util.Map;

public class CustomAPIAuthenticationHandler extends AbstractHandler {

    public boolean handleRequest(MessageContext messageContext) {
        try {
            if (authenticate(messageContext)) {
                return true;
            }
        } catch (APISecurityException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean handleResponse(MessageContext messageContext) {
        return true;  
    }

    public boolean authenticate(MessageContext synCtx) throws APISecurityException {
        Map headers = getTransportHeaders(synCtx);
        String authHeader = getAuthorizationHeader(headers);
        if (authHeader.startsWith("userName")) {
            return true;
        }
        return false;
    }

    private String getAuthorizationHeader(Map headers) {
        return (String) headers.get("Authorization");
    }

    private Map getTransportHeaders(MessageContext messageContext) {
        return (Map) ((Axis2MessageContext) messageContext).getAxis2MessageContext().
                getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    }
}

  • Build the above class and copy the jar file to <AM_HOME>/repository/components/lib folder where <AM_HOME> is the root of the WSO2 API Manager distribution.
  •  You can engage this handler to the API through the Management Console. Log in to the console and select 'Service Bus > Source View' in the 'Main' menu.
  •  In the ESB configuration that opens, you can see following line as the first handler in the API, which is the current authentication handler used in API Manager. 
 
<handler class="org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler"/>

Replace it with the one that we created.

  
<handler class="org.wso2.carbon.apimgt.gateway.handlers.security.CustomAPIAuthenticationHandler"/>