Custom authentication handler to perform either Basic authentication or Oauth2 in the API consuming process

Savithri Nandadasa

With the current implementations of the wso2 API Manager, It does not support both basic authentication and Oauth2 options for API consuming process. Therefore I implemented a sample custom handler to fulfil this requirement.

Corresponding authentication type is implemented using a handler and it is defined in the generated synapse API. Since there is not any configuration or UI to change which authentication type to be engaged, we need to define the corresponding handler in the synapse API. For that, we have to add a rule to template decide which authentication handler to use.

Also, with the custom attributes, we can selectively engage the basic authentication handler through the velocity template.

The basic authenticator authenticates the end user with the connected user store using the provided username and password.

According to the implementation of the handler, we use the header information to invoke basic authentication. So, if the header has “Authorization: Basic <base64 encoded key>”, then trigger basic authentication.

I have shared the code in [1] in order for you to get a better understanding of what I have implemented.

Please follow the steps below to configure the ExtendedOauthHandler in your environment.

  1. Place the handler (ExtendedOauthHandler-1.0-SNAPSHOT.jar) inside /repository/components/lib. Once you do this restart the server. Go to your API configuration file inside /repository/deployments/server/synapse-configs/default/api/ and do the following changes manually.
  2. Remove the default APIAuthenticationHandler from the list of handlers
<handler class=""/>

3. Add the sample ExtendedOauthHandler in place of the default handler as below

<handler class="org.wso2.OauthExtHandler.ExtendedOauthHandler">
<property name="deploymentPattern" value="ALL_IN_ONE"/>
<property name="clientKey" value="s1ydlgyj0FoqVktMNIMJtOVgA2Qa"/>
<property name="clientSecret" value="igibwC7yuV09AYyAYnhLzfJg2Zwa"/>

Please refer following curl commands to perform either Basic Authentication or Oauth2 in the API Consuming process.

Curl Command for Basic Authentication

curl -k -X GET "" -H  "accept: application/json" -H  "Authorization: Basic YWRtaW46YWRtaW4="

Curl Command for Bearer Token

curl -k -X GET "" -H  "accept: application/json" -H  "Authorization: Bearer 0f3c428c-b504-3ed4-9ef0-48b81f7260c7"


Hope you find this article useful! Until my next piece, happy coding!

Savithri Nandadasa

Written by

Software Engineer at WSO2

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade