Skip to main content
Skip table of contents

Invoking OAuth and Caching Access Tokens

Cache policies can be used to improve the performance of APIs by enabling the API proxy to store and retrieve data at runtime. This use case explains the usage of Cache, Service Call Out and Assign Variables policies to store and use access tokens.

 Use Case

For APIs secured with OAuth, Access Token is obtained from the token endpoint provided and passed on to the API with every request. This token can be cached using Populate cache policy and looked up using Lookup policy for subsequent requests. The Invalidate cache can be used to remove the token entry from the cache.

Policies used in the Use Case

  • Populate CacheTo insert data into the cache. Policy configuration contains a source element which is extracted from the request to the proxy and added to the cache.
  • Lookup CacheTo lookup data added in the cache. Looked up value is updated to a variable present in the input message which can be configured within the policy configuration.
  • Assign VariablesTo define variables from different parts of a message and provide them as inputs to other policies or to the target server. 
  • Service Call OutTo call external targets. In this case, Access Token endpoint to obtain tokens.
  • Invalidate CacheTo purge the data cached using Populate Cache policy.

Pre Conditions

  • Target API is secured with OAuth.
  • client_id and client_secret required for the access token endpoint are provided by the API owner.

Creating the Project

Perform the following actions to configure the project:

  1. Create a project and set OAuth-secured API URL as the Backend Service URL. The corresponding resource will be created by the name Default Resource.



  2. Navigate to Targets and add a new target for the Access Token endpoint. This target is required in Service Call Out policy to obtain access tokens.



  3. Configure the following policies in PROXY_REQUEST scope in the order shown below:
    a. lookupToken - Lookup Cache Policy
    b. setTokenExists - Assign Variables Policy
    c. tokenService - Service Call Out Policy
    d. assignToken - Assign Variables Policy
    e. populateToken - Populate Cache Policy


Steps to achieve the Use Case

Lookup Token if present in Cache

Look up Cache policy is used to fetch the token, if any, from the cache. The following configuration is needed to achieve the use case.

  • Cache Name: <Cache Name used in Populate Cache policy>

  • Key:

    • Type: CONSTANT
    • Default Value: token
    • Assign Value to Variable: target.request.query.access_token

Set the flag 'isTokenExists' and other parameters to invoke the Token Endpoint

Assign Variables Policy to set flag "isTokenExists" which is used to check whether the access token is looked up from cache or not. JavaScript is used to set this flag. The rest of the policies required for obtaining access token is applied based on this flag. If a token is available in the cache, then this flag will be set to 'true' and the remaining policies will be skipped. This policy also sets some parameters required for a token endpoint which are sent in the request (client_id, client_secret, grant_type)

  1. isTokenExists: Add a variable, rename it to "isTokenExists"
    • Source: JAVASCRIPT
    • Value

      JS
      function isTokenExists() {
          if(context.getVariable("target.request.query.access_token") == null){
              return "false";
          }
          else{
              return "true";
          }
      }
      isTokenExists();



  2. target.request.form.client_id: Fetching the client_id value from the input request and assigning it to the form parameter 'target.request.form.client_id'.
    Add a variable, rename it to 'target.request.form.client_id' and set the values below:
    • Source: QUERY_PARAM
    • Param Name: client_id



  3. target.request.form.client_secret: Fetching the client_id value from the input request and assigning it to the variable 'target.request.form.client_secret'.
    Add a variable, rename it to 'target.request.form.client_secret' and set the values below:
    • Source: QUERY_PARAM
    • Param Name: client_secret



  4. target.request.form.grant_type: Setting grant_type, which is client_credentials in this example to get access tokens.
    Add a variable, rename it to 'target.request.form.grant_type' and set the values below:
    • Source: CONSTANT
    • Value: client_credentials



  5. target.request.header.Content-Type:
    Add a variable, rename it to 'target.request.header.Content-Type' and set the values below:

    • Source: CONSTANT

    • Value: application/x-www-form-urlencode

Invoke Token Service to obtain Access Token

  1. Configure Service Call Out policy to invoke the access token Target and retrieve the required access tokens.




  2. Add a rule to check isTokenExists flag. This policy will be applied only if the access token is not present in the cache
     



    If the access token is not present in the cache, a request is sent to Token End Point which gives an access token in response. This request to Token EndPoint requires grant type, client id and client secret which are fetched from the variables set in setTokenExists(Assign Variables) policy.

Assign Token to a variable to populate Cache and to invoke Target Service

On successful execution, response JSON from tokenService contains an access token which needs to be extracted using the Assign Variables Policy and set the access_token query parameter. The configuration contains the JSON path to extract the token and a rule to check the isTokenExists flag. Add a variable, double-click on the variable name to rename it 'target.request.query.access_token' and set the values below:

  • Source: PAYLOAD
  • JSON Path: $access_token


Insert Token into Cache to improve performance

Populate Cache Policy to add the access token obtained from the above step into the cache. This token will be used in subsequent requests until it expires from the cache. Cache time to live can be configured depending on the access token expiry time provided by the token endpoint. The rule to check isTokenExists flag is added to this policy as well.

  • Cache Name: <can be any value>
  • Key:
    • Type: CONSTANT
    • Default Value: token

  • Value Source:
    • Type: CONTEXT_VARIABLE
    • Variable Name: target.request.query.access_token
    • Default Value: <can be any value>
  • Time to Idle Seconds: <can be any value>
  • Time to live Seconds: <can be any value> (Should be less than or equal to the access token expiry time)

Save and deploy the project after completing configurations.

Testing with POSTMAN Rest Client

Request and Response of Back end API without access token

'Missing OAuth token' exception is thrown as the backend is secured.

Request and Response of Access Token End Point

Token endpoint returns a JSON response containing access_token as shown in the figure below.

 

Request and Response of Integrated Project

client_id and client_secret are sent as query parameters. Assign Variable policy is used to prepare an appropriate POST request (form-urlencoded) required for the token endpoint using these parameters. The token obtained is cached before sending it to the backend API. Subsequent requests use this cached token instead of requesting the token from the token endpoint to improve performance.

Purging Cache using Invalidate Cache policy

Configure an Invalidate Cache policy in this or in a different project. Use the same Cache Name and Key used in Populate Cache policy.


When a request with this policy is processed, it will purge the data cached in Populate Cache policy. This cache can be completely deleted when 'Delete Cache' is enabled.



JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.