Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagehtml/xml
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);
    }
}

Follow the steps below to write a custom authentication handler.

  1. Implement the custom handler according to the above example.
  2. Build the class and copy the JAR file to <PRODUCT_HOME>/repository/components/lib/ folder.
  3. Log in to the management console and click Service Bus and then click Source View in the Main menu.
  4. In the ESB configuration that opens, the following line appears. This is the current authentication handler used in App Manager.

    Code Block
    languagexml
    <handler class="org.wso2.carbon.appmgt.gateway.handlers.security.saml2.SAML2AuthenticationHandler"/>
  5. Replace the above line with the handler that you created to engage your custom handler to the App Manager instance. According to this example, it is as follows:

    Code Block
    languagehtml/xml
    <handler class="org.wso2.carbon.appmgt.gateway.handlers.security.saml2.CustomAPIAuthenticationHandler"/>