Building an OAuth2 Token Generator API with SAP BTP APIM

In this post, I will provide a sequence of steps required to develop an API that generates an OAuth2 token, which can be utilized by other APIs within the same BTP instance for authorization purposes. Let's dive in.

Requirement

To develop an API capable of generating an OAuth2 token and prepare it to be used by other APIs within the same BTP instance.

Step #1. What is OAuth2?

For an understanding of OAuth2, please refer to the official docs.

See OAuth 2.0

Step 2. Create a new API

Utilizing the SAP BTP Integration Suite, create a new API specifically designed to generate the OAuth2 token. Ensure that the new API is built around a non-specific URL, such as 'https://local.com/' or a similar placeholder.

Step 3. Assign the new policy

In the PreFlow section of the API, add the 'OAuth v2.0' policy to generate the OAuth2 token.

Configure the policy settings accordingly.

Save the changes and deploy the API.

Step 4. Create the Product

Please refer to the official documentation for detailed instructions.

See Create a Product

Don't forget to include the API that generates the OAuth2 token in the newly created Product and publish.

Step 5. Create the Application

Navigate to the API Business HUB Enterprise cockpit and switch to the 'My Workplace' tab.

Create a new Application and add the recently created Product to it. Save the changes.

If you encounter difficulties while saving the application, please ensure that the Developer role is assigned to the user you are currently working with. To check this, navigate to the 'Manage' tab.

Step 6. Testing

For testing purposes, I created an API that utilizes the OpenWeather services.

Add the 'Verification OAuth2 token' policy to this API.

If you attempt to run the API directly via the link generated by the APIM, it will not function.

This is because a valid token needs to be provided using the API created at the beginning of this post.

To address this issue, open the Postman client and create a new request.

In the Authorization tab, select the 'OAuth2.0' type.

Then, provide the URL of the API that generates an OAuth2 token in the 'Access Token URL' field

For the Client ID and Client Secret fields, use the values from the API Business Hub Enterprise, specifically from the Application created in Step #5.

N.B. Ensure to assign the API to the corresponding Product (Refer to Step 4: Create the Product).

Click the 'Get New Access Token' button in Postman

Click the 'Proceed' button

Confirm with the newly generated token

Though it was a lengthy process, it was interesting. Thank you for your attention. You're awesome!

Read more