How to Implement OAuth 2.0 using Mule OAuth 2.0 Provider

How to Implement OAuth 2.0 using Mule OAuth 2.0 Provider

In this tutorial, we will demonstrate step by step guide to implement OAuth 2.0 using Mule OAuth 2.0 Provider in Mule 4.

What is OAuth 2.0?

OAuth 2.0 is secure protocol that allows a user to grant third-party web site or applications to access user’s protected resource without revealing the underlying credentials.

Who is OAuth Providers?

It is a software which provides the secure token to the client and validates the token. There are many third party OAuth providers like Auth0, Okta, Git, Salesforce, etc.,

Fortunately MuleSoft also have its own OAuth provider – We are going to discuss more about it with example.

Read this Auth0 official documentation to understand more about OAuth 2.0 framework.

oauth_flow_diagram

What is Mule OAuth 2.0 Provider?

Mule OAuth 2.0 Provider is an OAuth 2.0 provider alternative developed by MuleSoft that can be used in any MuleSoft API Platform organization, including the federated ones.

The modules available in Mule OAuth 2.0 provider are:

  1. CREATE CLIENT
  2. DELETE CLIENT
  3. VALIDATE TOKEN
  4. REVOKE TOKEN

Implementing Mule OAuth 2.0 Provider

Before get started, you must meet the below requirements:

  • Active Mule application deployedon Cloudhub/On-prem with Auto-discovery configuration.
  • Generate the client_id and client_secret. Don’t use your environment or organization credentials.
  • Any REST Client to perform Mule OAuth provider operations. We will use postman.

Follow below steps to implement the Mule OAuth 2.0 provider in Mule 4.

Step 1: Create a Mule project and name it as mule-oauth-provider.

Step 2: Create two global Object Store configurations to store Clients credentials and access tokens.

client_object_store

Create another Object Store and change the name to token_object_store.

Step 3: Create global OAuth 2.0 provider configurations as follows

Provider name: Mule_OAuth_Provider
Listener config: Create new HTTP Listener configuration.
Client validation rate limiter: Leave the default settings.
Client store: Refer the client_object_store
Supported gran types: CLIENT_CREDENTIALS
Token config: Edit inline
   Path: /token
   Token store: Refer the token_object_store

Leave the other default settings as is.
oauth-config1

Token config:

oauth-config2

CREATE CLIENT:

Step 1: Add HTTP Listener and refer the exiting listener configuration.

create-client-config

Step 2: Add Create Client operation and configure as follows

create-client-configuration

Other empty fields are optional and you can configure as per your business needs.

Step 3: Add transform message and set some response message such as Client has been created.

The create-client flow would look like:

create-client-flow

GET CLIENT:

There is no such operation in OAuth 2.0 provider module and its a inbuilt process. Do you remember that we have already configured the Token configuration in OAuth provider module.

token-config

VALIDATE TOKEN:

Step 1: Create a new flow with HTTP Listener configure as follows

validate-token-http

Step 1: Add Validate Token operation and configure as follows

validate-token-config

The Access token script is auto populated by default. Its simply splitting the message and accessing the second part.

We will pass the access token in the authorization header as follows.

auth-header

For examle,

access_token

Your Mule flow would look like

mule oauth 2.0 provider

That’s it! Now we have developed the Mule OAuth provider with following endpoints.

Create Client : http://<<host:port>>/createClient
Get Token: http://<<host:port>>/token
Validate Token: http://<<host:port>>/validate

Now deploy the Mule OAuth provider application.

deployment-status

Applying OAuth 2.0 Policy

Now let’s apply the Mule OAuth 2.0 policy to the API that we deployed earlier (not the above developed application).

Step 1: Update your API Specification with below code (securitySchemes and securedBy) and publish API Spec.

Sample API Specification:

#%RAML 1.0
title: Employees Exp API

securitySchemes:
  oauth_2_0:
    description: |
      This API supports OAuth 2.0 for authenticating all API requests.
    type: OAuth 2.0
    describedBy:
      headers:
        authorization:
          description: |
             Used to send a valid OAuth 2 access token. Do not use with the "access_token" query
             string parameter.
          type: string
      queryParameters:
        access_token:
          description: |
             Used to send a valid OAuth 2 access token. Do not use together with the "Authorization"
             header
          type: string
      responses:
        400:
          description: Invalid token.
        401:
          description: |
            Unauthorized or Connection error when connecting to the authorization server.
        403:
          description: |
            Forbidden, invalid client application credentials.
        500:
          description: |
            Bad response from authorization server, or WSDL SOAP Fault error.

/employees:
  get:
    securedBy:
      - oauth_2_0
    responses:
      200:
        body:
          application/json:
            example: !include /examples/listEmployees.json
              

Step 2: Go to API Manager and open the API you want to secure. In our case, Employees Exp API and update the Asset Version to latest version.

update-asset-version

Step 3: Click on Policies, Apply New Policy and search for OAuth 2.0 access token enforcement using Mule OAuth provider.

Step 4: Select latest version and click on Configure Policy.

select-latest-version

Step 4: Leave all default values as is and provide your OAuth provider validate endpoint.

access_token-endpoint

You can get the host name from the Runtime manager.

app-endpoint

Testing Mule OAuth 2.0 Provider

Now let’s see how our Mule OAuth 2.0 will secure our Mule API’s.

Step 1: First we will need to create client. This step is performed by developers. Its like registering Client application.

create-client-postman

Step 2: Get an access token by providing the client_id, client_secret and the grant type as follows,

get-access-token-postman

Step 3:

Scenarios#1: Access API without passing the access token.

access-api-without-token

Scenario#2: Access API with invalid access token.

access-api-with-invalid-token

Scenario#3: Access API with valid access token.

access-api-with-valid-token

In simple steps,

  1. Create a client using Create client operation.
  2. Retrieve access token using /token endpoint as we don’t have separate operation.
  3. Pass the access token in headers (Authorization) or in query parameters (access_token) depends on your security schemes snippet configuration.

Points To Remember

  • You will loose the data stored in the Object Store after 30 days so use private object store such as Redis if possible.
  • Another solution would be retrieve the keys for every 20 days and create clients again for every 20 days (not recommended for production).

We hope this article helped you to understand and implement the Mule OAuth 2.0 provider to secure Mule API’s using OAuth 2.0 policy.

If you face any issues while implementing the Mule OAuth 2.0 provider, please do let us know in the comment section.

Please do share it with your friends and don’t forget to follow us on Facebook, Twitter and LinkedIn. Visit our MuleSoft Hub for more tutorials and updates.

In this tutorial, we will demonstrate step by step guide to implement OAuth 2.0 using Mule OAuth 2.0 Provider in Mule 4.

What is OAuth 2.0?

OAuth 2.0 is secure protocol that allows a user to grant third-party web site or applications to access user’s protected resource without revealing the underlying credentials.

Who is OAuth Providers?

It is a software which provides the secure token to the client and validates the token. There are many third party OAuth providers like Auth0, Okta, Git, Salesforce, etc.,

Fortunately MuleSoft also have its own OAuth provider – We are going to discuss more about it with example.

Read this Auth0 official documentation to understand more about OAuth 2.0 framework.

oauth_flow_diagram

What is Mule OAuth 2.0 Provider?

Mule OAuth 2.0 Provider is an OAuth 2.0 provider alternative developed by MuleSoft that can be used in any MuleSoft API Platform organization, including the federated ones.

The modules available in Mule OAuth 2.0 provider are:

  1. CREATE CLIENT
  2. DELETE CLIENT
  3. VALIDATE TOKEN
  4. REVOKE TOKEN

Implementing Mule OAuth 2.0 Provider

Before get started, you must meet the below requirements:

  • Active Mule application deployedon Cloudhub/On-prem with Auto-discovery configuration.
  • Generate the client_id and client_secret. Don’t use your environment or organization credentials.
  • Any REST Client to perform Mule OAuth provider operations. We will use postman.

Follow below steps to implement the Mule OAuth 2.0 provider in Mule 4.

Step 1: Create a Mule project and name it as mule-oauth-provider.

Step 2: Create two global Object Store configurations to store Clients credentials and access tokens.

client_object_store

Create another Object Store and change the name to token_object_store.

Step 3: Create global OAuth 2.0 provider configurations as follows

Provider name: Mule_OAuth_Provider
Listener config: Create new HTTP Listener configuration.
Client validation rate limiter: Leave the default settings.
Client store: Refer the client_object_store
Supported gran types: CLIENT_CREDENTIALS
Token config: Edit inline
   Path: /token
   Token store: Refer the token_object_store

Leave the other default settings as is.
oauth-config1

Token config:

oauth-config2

CREATE CLIENT:

Step 1: Add HTTP Listener and refer the exiting listener configuration.

create-client-config

Step 2: Add Create Client operation and configure as follows

create-client-configuration

Other empty fields are optional and you can configure as per your business needs.

Step 3: Add transform message and set some response message such as Client has been created.

The create-client flow would look like:

create-client-flow

GET CLIENT:

There is no such operation in OAuth 2.0 provider module and its a inbuilt process. Do you remember that we have already configured the Token configuration in OAuth provider module.

token-config

VALIDATE TOKEN:

Step 1: Create a new flow with HTTP Listener configure as follows

validate-token-http

Step 1: Add Validate Token operation and configure as follows

validate-token-config

The Access token script is auto populated by default. Its simply splitting the message and accessing the second part.

We will pass the access token in the authorization header as follows.

auth-header

For examle,

access_token

Your Mule flow would look like

mule oauth 2.0 provider

That’s it! Now we have developed the Mule OAuth provider with following endpoints.

Create Client : http://<<host:port>>/createClient
Get Token: http://<<host:port>>/token
Validate Token: http://<<host:port>>/validate

Now deploy the Mule OAuth provider application.

deployment-status

Applying OAuth 2.0 Policy

Now let’s apply the Mule OAuth 2.0 policy to the API that we deployed earlier (not the above developed application).

Step 1: Update your API Specification with below code (securitySchemes and securedBy) and publish API Spec.

Sample API Specification:

#%RAML 1.0
title: Employees Exp API

securitySchemes:
  oauth_2_0:
    description: |
      This API supports OAuth 2.0 for authenticating all API requests.
    type: OAuth 2.0
    describedBy:
      headers:
        authorization:
          description: |
             Used to send a valid OAuth 2 access token. Do not use with the "access_token" query
             string parameter.
          type: string
      queryParameters:
        access_token:
          description: |
             Used to send a valid OAuth 2 access token. Do not use together with the "Authorization"
             header
          type: string
      responses:
        400:
          description: Invalid token.
        401:
          description: |
            Unauthorized or Connection error when connecting to the authorization server.
        403:
          description: |
            Forbidden, invalid client application credentials.
        500:
          description: |
            Bad response from authorization server, or WSDL SOAP Fault error.

/employees:
  get:
    securedBy:
      - oauth_2_0
    responses:
      200:
        body:
          application/json:
            example: !include /examples/listEmployees.json
              

Step 2: Go to API Manager and open the API you want to secure. In our case, Employees Exp API and update the Asset Version to latest version.

update-asset-version

Step 3: Click on Policies, Apply New Policy and search for OAuth 2.0 access token enforcement using Mule OAuth provider.

Step 4: Select latest version and click on Configure Policy.

select-latest-version

Step 4: Leave all default values as is and provide your OAuth provider validate endpoint.

access_token-endpoint

You can get the host name from the Runtime manager.

app-endpoint

Testing Mule OAuth 2.0 Provider

Now let’s see how our Mule OAuth 2.0 will secure our Mule API’s.

Step 1: First we will need to create client. This step is performed by developers. Its like registering Client application.

create-client-postman

Step 2: Get an access token by providing the client_id, client_secret and the grant type as follows,

get-access-token-postman

Step 3:

Scenarios#1: Access API without passing the access token.

access-api-without-token

Scenario#2: Access API with invalid access token.

access-api-with-invalid-token

Scenario#3: Access API with valid access token.

access-api-with-valid-token

In simple steps,

  1. Create a client using Create client operation.
  2. Retrieve access token using /token endpoint as we don’t have separate operation.
  3. Pass the access token in headers (Authorization) or in query parameters (access_token) depends on your security schemes snippet configuration.

Points To Remember

  • You will loose the data stored in the Object Store after 30 days so use private object store such as Redis if possible.
  • Another solution would be retrieve the keys for every 20 days and create clients again for every 20 days (not recommended for production).

We hope this article helped you to understand and implement the Mule OAuth 2.0 provider to secure Mule API’s using OAuth 2.0 policy.

If you face any issues while implementing the Mule OAuth 2.0 provider, please do let us know in the comment section.

Please do share it with your friends and don’t forget to follow us on Facebook, Twitter and LinkedIn. Visit our MuleSoft Hub for more tutorials and updates.

7 COMMENTS

  1. What happens if the response is “error”: “Authentication denied.”

    I’m following all the steps but I’m getting this message.

    • Can you please check your API Spec. As per above Spec, you should pass the access token either in headers (authorization) or query params (access_token).

      Also try to access without token and see what kind of response you will get.

      • Hi Vanchiv, thanks for your answer.

        Yes, I generated the client_id and client_secret and I created the new client with these values. Then I generate the token and this is sent by header.
        I have 3 scenarios:
        1- I did not send the header (authorization)
        response: “error”: “Access token was not provided”

        2- I send an invalid token
        response: “error”: “The token received: tWDMtv2xQrN5eiJrm8yukO4IlF23PDI2-do2O0n7uNbABwQf3X7bEl88QApMA_Me-qc5qDYgI_xnqCyF7oQ4Lw1 , is not valid”

        3- I send a valid token
        response: “error”: “Authentication denied.”

        I wanted to know if this is due to a permissions issue on the platform or if I have to do any additional configuration.
        As you can see, scenario #3 it should allow the API to be consumed correctly since the token is the correct one.

        I already reviewed the specification in detail, the policy added, but there is no problem. I think it is a permission issue but I am not sure.

        • Hi Anthony, can you please attach your postman collection here, If you are deployed your app on your personal account.

          You can also try to validate your token using /validate endpoint.

          Below are our sample endpoints:

          Create Client : mule-oauth-provider-vanchiv.us-e2.cloudhub.io/createClient

          client_id: 4a12f219c82043749f7615d653ea5145
          client_secret: 93a1072D4b664492A6D2e8389744BD6b
          client_name : Salesforce

          Get Token: mule-oauth-provider-vanchiv.us-e2.cloudhub.io/token

          use the same client_id and secret and add grant_type = CLIENT_CREDENTIALS.

          API: vv-emp-xapi.us-e2.cloudhub.io/api/employees

          query_params : access_token.

          Please try to access the above API and will verify from our end.

  2. What about refresh token scenario. If we configured to use single refresh token, how we need to pass it to oauth2.0 provider to get access token refreshed?

  3. I got an error at last step : “error”“Cannot construct instance of java.util.LinkedHashMap (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value (‘12345’)\n at [Source: (String)\”\”12345\”\”; line: 1, column: 1]”

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Related Articles

How to Create Multiple Folders at Once in Windows 10

Creating folders and subfolders manually is time consuming tasks...

How to Integrate Solace with MuleSoft using JMS API

In this tutorial, we will demonstrate step by step...

How to Open Port on AWS EC2 Instance

In this tutorial, we will demonstrate step by step...

7 COMMENTS

  1. What happens if the response is “error”: “Authentication denied.”

    I’m following all the steps but I’m getting this message.

    • Can you please check your API Spec. As per above Spec, you should pass the access token either in headers (authorization) or query params (access_token).

      Also try to access without token and see what kind of response you will get.

      • Hi Vanchiv, thanks for your answer.

        Yes, I generated the client_id and client_secret and I created the new client with these values. Then I generate the token and this is sent by header.
        I have 3 scenarios:
        1- I did not send the header (authorization)
        response: “error”: “Access token was not provided”

        2- I send an invalid token
        response: “error”: “The token received: tWDMtv2xQrN5eiJrm8yukO4IlF23PDI2-do2O0n7uNbABwQf3X7bEl88QApMA_Me-qc5qDYgI_xnqCyF7oQ4Lw1 , is not valid”

        3- I send a valid token
        response: “error”: “Authentication denied.”

        I wanted to know if this is due to a permissions issue on the platform or if I have to do any additional configuration.
        As you can see, scenario #3 it should allow the API to be consumed correctly since the token is the correct one.

        I already reviewed the specification in detail, the policy added, but there is no problem. I think it is a permission issue but I am not sure.

        • Hi Anthony, can you please attach your postman collection here, If you are deployed your app on your personal account.

          You can also try to validate your token using /validate endpoint.

          Below are our sample endpoints:

          Create Client : mule-oauth-provider-vanchiv.us-e2.cloudhub.io/createClient

          client_id: 4a12f219c82043749f7615d653ea5145
          client_secret: 93a1072D4b664492A6D2e8389744BD6b
          client_name : Salesforce

          Get Token: mule-oauth-provider-vanchiv.us-e2.cloudhub.io/token

          use the same client_id and secret and add grant_type = CLIENT_CREDENTIALS.

          API: vv-emp-xapi.us-e2.cloudhub.io/api/employees

          query_params : access_token.

          Please try to access the above API and will verify from our end.

  2. What about refresh token scenario. If we configured to use single refresh token, how we need to pass it to oauth2.0 provider to get access token refreshed?

  3. I got an error at last step : “error”“Cannot construct instance of java.util.LinkedHashMap (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value (‘12345’)\n at [Source: (String)\”\”12345\”\”; line: 1, column: 1]”

LEAVE A REPLY

Please enter your comment!
Please enter your name here