How to secure SpringBoot REST APIs using AWS Cognito OAuth2 scopes?

karthik
2 min readDec 29, 2023

In this blog, I will explain how to secure APIs that are built using SpringBoot framework using AWS Cognito access tokens and OAuth2 scopes.

Use Case

In modern application development, APIs are one of the main components. Securing these APIs is very critical for any organization to avoid any major cyber security attacks. One of the most commonly used security pattern is using OAuth2 scopes. Refer this RFC to learn more about OAuth2 specification.

For this blog, I will use OAuth2 client credentials grant.

The below diagram explains the high level architecture and the video explains the step-by-step instructions to configure and test this use case.

  1. Client app calls the AWS Cognito’s /oauth2/token endpoint using client_credentials grant.
  2. Cognito will return a JWT access token with the scopes that are already configured.
  3. Client app will call the APIs hosted in SpringBoot app by passing the JWT access token in the Authorization header.
  4. SpringBoot app will validate the JWT token that includes signature validation, scope validation and other claims validation.

5a. If all the validations are successful, API will return a successful response.

5b. If the token passed in the header is invalid, API will return a 401 unauthorized error.

5c. If the token is valid, but doesn’t have the required permissions, API will return 403 Forbidden error.

How to secure SpringBoot REST APIs using AWS Cognito OAuth2 scopes?

Key points to note

  • Cognito documentation to create a app client.
  • SpringBoot official documentation to configure a resource server
  • SpringBoot provides out of the box support for securing APIs using OAuth2 scopes

Thanks for reading this article. Please subscribe to the below YouTube channel and follow me in medium to learn about security and IAM.

--

--