Integrate Spring Boot Resource Server with Cognito Identity Provider

Let us use Cognito as an Idp to protect our resources. We will be using spring security to do the same in our spring boot backend.

In the previous tutorial, I showed how to get the access token(JWT) in front-end using Amplify. We will be passing that token from frontend to the resource server. Resource server will validate the token using JWK (JSON Web Key) and if it is valid, will process the request based on Roles.

If you have an ECS service, you can also expose HTTPS Authorized API via API-Gateway. Read more in here: Expose ECS Service via API Gateway.

Please fork the complete project from my Github.

Spring Boot Resource Server

Spring security configuration

This is the core part. Here we are converting the Cognito claims to Spring security consumable format.

For Authorization, we will make use of Cognito Groups. We create two groups, ROLE_ADMIN & ROLE_EMPLOYEE. We map users to each group. When the user is authenticated, we get the Cognito group as claims. We make use of this to set Spring Security Authorities for the user.

Groups in Cognito

Note:

  1. You need not provide client secret. (For PKCE, we don’t create client secrete)
  2. We only need to provide one App Client Id registered in the User Pool. This can be used to validate the access-token from multiple App Clients registered within that User Pool. ( ie If you have 1 App Client for mobile app, 1 App Client for the web app, in the resource server, you only need to specify 1 among them. )
  • AdminController : Endpoint accessible only to admins.
  • EmployeeController
  • PublicController

Now, you have everything ready locally. Please do one round of testing to check if the flow is working fine.

In the next tutorial, we will deploy the apps in AWS and test it with Cognito.

Found it Interesting?
Please show your support by 👏.

Writes on Big Data, AWS & Backend technologies.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store