AWS+SAP: AWS Cognito and JWT w/ Exposed RFC in REST
Tags: authentication, awscognito, saprest, sap
Published: 2023-02-12 00:05:48

---
title: AWS+SAP: AWS Cognito and JWT w/ Exposed RFC in REST
published: true
date: 2023-02-11 06:29:07 UTC
tags: authentication,awscognito,saprest,sap
canonical_url: https://medium.com/fair-experience-insights/aws-sap-aws-cognito-and-jwt-w-exposed-rfc-in-rest-ee4842475fda
---

_Note; This is technically part 2 focusing more on how to configure AWS Cognito to work with SAP API Management; if you are interested in SAP API Management and policies, go [here](https://dev.to/kazimurtaza/how-to-jwt-with-sap-api-management-3j0k)

One of our customers who run SAP workloads on Amazon Web Services (AWS) was interested in reviewing how to integrate their user pool securely with a backend-exposed RFC without putting anything at risk. To help shed light on the matter, we decided to dive into the topic and put together this blog post. The post will discuss best practices for securely integrating a user pool with an exposed RFC for those running SAP workloads on AWS. This post is suitable for both seasoned SAP professionals and beginners.

Securely integrating a user pool with an exposed RFC is crucial for organizations running SAP workloads on AWS. Amazon Web Services (AWS) offers various services that can be leveraged to secure the integration process, but it can take time to determine the best approach. In this blog post, we’ll focus on using AWS Cognito and JSON Web Tokens (JWT) to secure the integration between a user pool and an exposed RFC in REST.

**AWS Cognito:**

AWS Cognito is a user management and authentication service that provides sign-up and sign-in functionality for web and mobile applications. It integrates with other AWS services, including AWS AppSync, AWS Lambda, and AWS Identity and Access Management (IAM). Cognito provides a secure and scalable solution for user authentication, which is essential for ensuring your integration’s security.

**JSON Web Tokens (JWT):**

JWT is a compact, URL-safe means of representing claims to be transferred between two parties. JWT tokens contain encoded information, including user identity, which can be used to authenticate the user and authorize access to the application or API. JWT tokens are signed, ensuring the token’s authenticity and integrity. Using JWT tokens, you can securely authenticate a user and grant access to the exposed RFC without risking the user’s credentials.

**Integration Steps:**

1. Create a user pool in AWS Cognito and configure the necessary settings,
2. Create a REST API endpoint in SAP API Management to expose the RFC wrapped using SAP Cloud Integration for request and response transformation,
3. Secure the REST API endpoint in SAP API Management using the AWS Cognito certificate and configure the necessary authorization policies.
4. Pass the JWT token in the request header when accessing the exposed RFC.
5. Validate the JWT token in SAP API Management Policies.
6. Grant or deny access to the exposed RFC based on the validation result.

![](https://cdn-images-1.medium.com/max/1024/1*TxnPT2trwwIP029ZTn5Kmw.png)

**Let us go through the flow shown in the diagram above;**

1. The user sends a request to the Commerce Storefront with a valid username and password.
2. The server authenticates the user and creates a unique JWT token with help from Cognito.
3. The server sends the JWT token back to the user.
4. The user then stores the JWT token in their local storage.

- The user retrieves some details from the exposed RFC and sends the SAP API Management with the JWT token.
- The server verifies the JWT token and grants access to the requested resource.

**How to configure AWS Cognito;**

1. Create a user pool

![](https://cdn-images-1.medium.com/max/1024/1*w3pFdHcTLYZaQmfCzGfx2w.png)

2. Configure the Password policy  
AWS has options to provide enhanced security settings for passwords, also to force MFA or not;

![](https://cdn-images-1.medium.com/max/900/1*yrbf-hO8Y9MrAHV4z-X3-A.png)

![](https://cdn-images-1.medium.com/max/807/1*aMF7UZGYn8n0HikVGb036A.png)

With what recovery options to set. Next, you configure the sign-in experience to suit your environment best; since this is a POC and we are developers, we would more or less play with the API(s) and wouldn’t be too worried about that now.

3. Name your user pool

![](https://cdn-images-1.medium.com/max/824/1*y6W7vxjWNtrViXBiryWxiA.png)

4. Important step;

![](https://cdn-images-1.medium.com/max/799/1*_lp46QFFiaPFxQrpAtm0iA.png)

We do not require Hosted UI for login and sign-up pages since everything will be taken by our Commerce Platform using API(s) to communicate with AWS Cognito. **Our Storefront will not save any secrets since that is how security incidents occur. CHOOSE Public client ** — Browser — Cognito API requests are made from the user systems that are not trusted with client secrets.

![](https://cdn-images-1.medium.com/max/728/1*ZB0KUdxz0P6cpM4nT6RVUw.png)

Enable the above user flows to enable API calls from our storefront.

![](https://cdn-images-1.medium.com/max/1024/1*t845Vjje7kxqEzmeDoP9QA.png)

The user pool was successfully created.

5. Extract the signing certificate;

![](https://cdn-images-1.medium.com/max/1024/1*QtRA_ifXAmu-SYYNIfboxQ.png)

![](https://cdn-images-1.medium.com/max/535/1*EBmXB5Qjvwgq3e5wMpAPyw.png)
_Copy and download this certificate because SAP APIM will use this to validate the JWT tokens sent in requests._

6. Populate the user pool with a demo user; we will take this a little ahead to verify if the user pool is configured correctly.

![](https://cdn-images-1.medium.com/max/776/1*xJn8h5r5RfQNlXIFBEFZyg.png)

When we create the user, we will be asked to force change the password to confirm the user; since we do not have hosted UI or anything, this could prove tricky for the uninitiated.

![](https://cdn-images-1.medium.com/max/1024/1*3SZvi1LI0YNTjDsDa3qDdQ.png)

7. Call the API to retrieve the Token;

```
curl --location --request POST 'https://cognito-idp.{{AWS_REGION}}.amazonaws.com/{{USER_POOL_ID}}' \
--header 'X-Amz-Target: AWSCognitoIdentityProviderService.InitiateAuth' \
--header 'Content-Type: application/x-amz-json-1.1' \
--header 'Accept-Language: application/json' \
--data-raw '{ 
    "AuthParameters": 
    { 
        "USERNAME": "{{cognitoUserName}}",
        "NEW_PASSWORD": "{{cognitoUserPassword}}"
    }, 
    "AuthFlow": "USER_PASSWORD_AUTH",
    "ClientId": "{{cognitoClientId}}" 
}'
```

To confirm when you call the API to request the JWT Token, you will be struck with this body;

```
{
    "ChallengeName": "NEW_PASSWORD_REQUIRED",
    "ChallengeParameters": {
        "USER_ID_FOR_SRP": "1a691d76-90f0-3632-b43f-432bbc3c9521",
        "requiredAttributes": "[]",
        "userAttributes": "{\"email\":\"qazi.murtaza@faircg.com\"}"
    },
    "Session": "AYABeP7KqCHXG4jBT-qEaysPJVsAHQABAAdTZXJ2aWNlABBDb2duaXRvVXNlclBvb2xzAAEAB2F3cy1rbXMAS2Fybjphd3M6a21zOnVzLWVhc3QtMTo3NDU2MjM0Njc1NTU6a2V5L2IxNTVhZmNhLWJmMjktNGVlZC1hZmQ4LWE5ZTA5MzY1M2RiZQC4AQIBAHiG0oCCDoro3IaeecGyxCZJOVZkUqttbPnF4J7Ar-5byAHO9OhZAb2T4rq0VCQMI_JOAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQM9uEKK3DcQe221qK4AgEQgDvVSvNMuXn8bkUQZm4g43xJN-o3LgAEUkUIqIrdhsggrTD4z9EvydNHKGTDAvgByNcDioFr-Dfkd9A0iAIAAAAADAAAEAAAAAAAAAAAAAAAAABx02tlgAn--Caj8aCy95pA _____ wAAAAEAAAAAAAAAAAAAAAEAAADVbgpubnsc-3rD1_9E6S-ahI0xjKa43e4KkLI_V2NsmAPMyHF5D73_rdUrl0XwhtKKN1qmz7WgYWwwRiaN3DQcAWB9Oa_ubLnuif2nRw_PZZx705iVCfgEs79B1rIxxEl9KC8wE6fawCMm-WgqUUqSG_5QP3jHDSQspY_Hb4hsI1qv9pPL3Ju81OfcbPwf0mnR5nk4DMXzwNzm9c5_nSHuzJejqunMEh7xAPI7q0kdL6z17BPmgPGhgTc29nheuBNt9pMgDPQ94kLV34cFfH7F78ZkMkObdjsKXm_wdrqqZCYtxx5BIg"
}
```

Don’t fret; call this below request to reset the password and you will be golden. Note the headers; they are important.

```
curl --location --request POST 'https://cognito-idp.{{AWS_REGION}}.amazonaws.com/{{USER_POOL_ID}}' \
--header 'X-Amz-Target: AWSCognitoIdentityProviderService.RespondToAuthChallenge ' \
--header 'Content-Type: application/x-amz-json-1.1' \
--header 'Accept-Language: application/json' \
--data-raw '{
    "ChallengeName": "NEW_PASSWORD_REQUIRED",
    "ChallengeResponses": {
        "USERNAME": "{{cognitoUserName}}",
        "NEW_PASSWORD": "{{cognitoUserPassword}}"
    },
    "ClientId": "{{cognitoClientId}}",
    "Session": "AY....Insert the session recieved in the preceeding call"
}'
```

Calling the first API again would wield the JWT Token with a 200 OK response.

```
{
    "AuthenticationResult": {
        "AccessToken": "e....yJraWQ.",
        "ExpiresIn": 3600,
        "IdToken": "eyJraWQiO...",
        "RefreshToken": "eyJjdHk....",
        "TokenType": "Bearer"
    },
    "ChallengeParameters": {}
}
```

Verify the token at [JWT.IO](http://jwt.io/);

![](https://cdn-images-1.medium.com/max/629/1*U_RZvcJo3_ClilmQrO6dsg.png)

**How to configure SAP API Management for JWT** ; read [here](https://kazimurtaza.medium.com/how-to-jwt-with-sap-api-management-dba9d712615f).

**Conclusion**

In conclusion, using AWS Cognito and JWT tokens is a secure and effective way to integrate a user pool with an exposed RFC for organizations running SAP workloads on AWS. By following the steps outlined in this post, you can ensure that your integration is secure and free from risk. Whether you’re a seasoned SAP professional or just starting, we hope this post has provided valuable information and insights into the best practices for securing your integration.

* * *