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
Cognito Access Token Converter:
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.
- You need not provide client secret. (For PKCE, we don’t create client secrete)
- 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.
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 👏.