Use Case
Cache policies can be used to improve performance of APIs by 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.
For APIs secured with OAuth, Access Token is obtained from the token endpoint provided and passed it to API with every request. This token can be cached using Populate cache policy and looked up using Lookup policy for subsequent requests. Invalidate cache can be used to remove the token entry from the cache.
Policies used in the Use Case
- Populate Cache: To insert data into the cache. Policy configuration contains a source element which is extracted from the request to proxy and added to the cache.
- Lookup Cache: To lookup data added in the cache. Looked up value is updated to a variable present in input message which can be configured in policy configuration.
- Assign Variables: To define variables from different parts of a message and provide them as inputs to other policies or target server.
- Service Call Out: To call external targets. In this case, Access Token endpoint to obtain tokens.
- Invalidate Cache: To purge the data cached using Populate Cache policy.
Pre Conditions
- Target API is secured with OAuth.
- client_id, client_secret required for access token endpoint are provided by API owner.
Creating the Project
To configure the project, perform the following actions:
- Create a project and set OAuth-secured API URL as Backend Service URL. The corresponding resource will be created by name Default Resource.
- Navigate to Targets and add a new target for Access Token endpoint. This target is required in Service Call Out policy to obtain access tokens.
- Configure following policies in PROXY_REQUEST scope in the order same as 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 from the cache if it exists. 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 Token Endpoint
Assign Variables Policy to set flag isTokenExists which is used to check whether 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 will be applied based on this flag. If a token is available in the cache, then this flag will be set to 'true' and remaining policies will be skipped. This policy also sets some parameters required for token endpoint which are sent in request(client_id, client_secret, grant_type)
- isTokenExists: Add a variable, rename it to "isTokenExists"
- Source: JAVASCRIPT
Value
- 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 below values:- Source: QUERY_PARAM
- Param Name: client_id
- 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 below values:- Source: QUERY_PARAM
- Param Name: client_secret
- 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 below values:- Source: CONSTANT
- Value: client_credentials
target.request.header.Content-Type:
Add a variable, rename it to 'target.request.header.Content-Type' and set the below values:Source: CONSTANT
Value: application/x-www-form-urlencode
Invoke Token Service to obtain Access Token
Configure Service Call Out policy to invoke the access token Target and get the required access tokens.
Add a rule to check isTokenExists flag. This policy will be applied only if access token is not present in cache
If access token is not present in the cache, a request is sent to Token End Point which gives 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 access token which needs to be extracted using Assign Variables Policy and set access_token query parameter. The configuration contains JSON path to extract token and a rule to check isTokenExists flag. Add a variable, double-click on the variable name to rename it to 'target.request.query.access_token' and set the below values:
- Source: PAYLOAD
- JSON Path: $access_token
Insert Token into Cache to improve performance
Populate Cache Policy to add 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. 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 access token expiry time in this case)
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 end point returns a JSON response containing access_token as shown in the figure below.
Request and Response of Integrated Project
client_id, client_secret are sent as query parameters. Assign Variable policy is used to prepare a proper POST request (form-urlencoded) required for token endpoint using these parameters. Token obtained is cached before sending it to backend API. Subsequent requests use this cached token instead of requesting the token from token endpoint to improve performance.
Purging Cache using Invalidate Cache policy
Configure an Invalidate Cache policy in the above 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.