Unknown macro: {next_previous_links}
Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

WSO2 API Manager provides OAuth2 bearer token as its default authentication mechanism. The source code of the implementation is here. Similarly, you can extend the API Manager to support any custom authentication mechanism by writing your own authentication handler class. This custom handler must extend org.apache.synapse.rest.AbstractHandler class and implement the handleRequest() and handleResponse() methods.

Given below is an example implementation:

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);
    }
}

After implementing the custom handler as explained above,

  1. Build the class and copy the jar file to <APIM_HOME>/repository/components/lib folder.
  2. Log in to the management console and select Service Bus > Source View in the Main menu.
  3. In the ESB configuration that opens, the following line appears as the first handler. This is the current authentication handler used in the API Manager.

    <handler class="org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler"/>
  4. Replace the above line with the handler that you created to engage your custom handler to the API Manager instance. According to this example, it is as follows:

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