Skip to main content

Google

How to Customize and Validate the Json Message for GrantType Access Token in Apigee

A man using a computer while 2 people observe

Overview

This use case describes how to customize and validates JSON message for GrantType client credential – AccessToken.

What is GrantType client credential?

Client POST’s an API call to Apigee with client ID and client secret to fetch the access token from the registered developer application. In addition, query parameter grant_type=client_credentials must be passed in the request. But in this blog, we are going to send clientId/secret and grantType in json payload.

Sequence Diagram

Sequencediagram

  • Client application sends Json Request to Apigee edge to fetch access token. Request contains clientId, clientSecret and grantType.
  • Request data validated against the OpenAPI Specification (Swagger).
  • If validation fails sends the error response.
  • Else edge authentication clientId and clientSecret.
  • If authentication fails sends error response.
  • Else edge returns the customized json success response.

Required applications to work on this usecase

  • Postman or any client application
  • APIGEE Edge

Problem definition

This document helps to solve technical challenges while configuring clientCredential grantType

Intended Audience

People who have knowledge (Developer/Administrator) in APIGEE EDGE.

Open API specification

Create a OpenAPI specification to define the structure of grant type access token RESTful API. Define client_id, client_secret and grant_Type as required request element. access_token, issued_at and expires_in are success response element.

Openapispec

Proxy Configuration

Create a no target proxy using the open API specification

Step 1: Develop->Proxy->No target->Click Use OpenAPI Spec
Step 2: Define Name, BasePath and description
Step 3: Select Policy as PassThrough

Proxyconfig

Policy Configurations

OpenAPI Spec validation policy
OAS Validation policy to validate the incoming json message against the open API specification.

Add OpenAPI Spec Validation policy and import the open API spec(Swagger) to validate the input message.

Oas Jsonvalidation

Extract Variables policy
Add Extract variable policy to set clientId/clientSecret/GratTypeas flow variable from the inputmessage.

Ev Flowvariable

Below is the snippet to extract flow variable,

<JSONPayload>
<Variable name="clientId">
<JSONPath>$.client_id</JSONPath>
</Variable>
<Variable name="clientSecret">
<JSONPath>$.client_secret</JSONPath>
</Variable>
<Variable name="grantType">
<JSONPath>$.grant_type</JSONPath>
</Variable>
</JSONPayload>

JavaScriptPolicy
Add JavaScript policy to set clientId/clientSecret to formparam and grantType to queryparam. Because by default OAuth2 policy reads clientCredential from.

var username = context.getVariable("clientId");
var password = context.getVariable("clientSecret");
var granttype = context.getVariable("grantType");
context.setVariable("request.queryparam.grant_type", granttype);
context.setVariable("request.formparam.client_id",username);
context.setVariable("request.formparam.client_secret", password);

OAuth2 Policy
Add Oauth2 policy to generate access token. This policy verifies the clientCredentails before sending the access token. Update below configuration to oauth2 policy,

<Operation>GenerateAccessToken</Operation>
<SupportedGrantTypes>
<GrantType>client_credentials</GrantType>
</SupportedGrantTypes>
<GrantType>request.queryparam.grant_type</GrantType>
<GenerateResponse enabled="false"/>

<GrantType>request.queryparam.grant_type</GrantType> – This tag tells oauth2 policy to fetch grantType value from queryparam grant_type.

<GenerateResponse enabled=”false”/> – This tag tells oauth2 policy to don’t genrate response automatically.

Assign Message Policy
Add assign message policy to create a customised json success response. Update the below snippet to policy,

<Set>
<StatusCode>200</StatusCode>
<ReasonPhrase>OK</ReasonPhrase>
<Payload contentType="application/json">{
"access_token" : "{oauthv2accesstoken.GenerateAccessTokenClient.access_token}",
"issued_at" : "{oauthv2accesstoken.GenerateAccessTokenClient.issued_at}",
"expires_in" : "{oauthv2accesstoken.GenerateAccessTokenClient.expires_in}"
}
</Payload>
</Set>
<AssignTo createNew="false" transport="http" type="response"/>

Add one more assign policy to handle the customised json error response. Update below snippet to policy,

<Set>
<StatusCode>500</StatusCode>
<ReasonPhrase>Internal Server Error</ReasonPhrase>
<Payload contentType="application/json">{
"ErrorResponse" : {
"errorMessage" : "{escapeJSON(error.message)}",
"errorCode" : "20030"
}
}
</Payload>
</Set>
<AssignTo createNew="false" transport="http" type="response"/>

Fault Rule
Add DefaultFaultRule step to handle error cases. It will be executed only if there is an exception / error in proxy flow. Refer Error response assign message policy to send customized error response.

<ProxyEndpoint name="default">
<DefaultFaultRule name="fault-rule">
<Step>
<Name>AM-ErrorResponse</Name>
</Step>
</DefaultFaultRule>
<PreFlow name="PreFlow">…….
…………..</ ProxyEndpoint >

Flow Design

Flowdesign

Deploy and Test

Deploy the proxy and test using the postman collection.

Happy Path Scenario
Happypath

Json validation error
OAS policy validates the incoming request and throws the validation error for grant_type field.
Failjsonvalidation

Authentication Failure Error
Oauth2 policy validates the clientcredential of registered users. If clientcredential not valid throws the error.
Failauth

Conclusion

This blog has shown you how to customize and validate JSON message for GrantType client credential to fetch access token. For more information on client credential grantType refer apigee docs.

Reference link: https://docs.apigee.com/api-platform/security/oauth/oauth-20-client-credentials-grant-type

Thoughts on “How to Customize and Validate the Json Message for GrantType Access Token in Apigee”

  1. I appreciate your kind words about the blog and the opportunity to express your thoughts. Your support means a lot, and I eagerly await your continued engagement with my future blogs. Thank you for recognizing my efforts, and I’m excited to provide you with more insightful content in the future.

    Here is sharing some Oracle Integration Cloud Service concepts may be its helpful to you.
    Oracle Integration Cloud Service

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Rajeshwari Dhamodaran

More from this Author

Follow Us