Secure your Spring Boot App with Json Web Tokens and OAuth 2.0 provided by AWS Cognito

Kevin Grüneberg
2 min readMar 26, 2020

Personally, I hate this topic. I do it every few years and by then I have forgotten everything I knew about OAuth flows and the confusion begins again.

This tutorial assumes that you separate your login app from your Spring Boot service and only want to verify the tokens and scopes in the app. Additionaly, I assume you have already set up AWS Cognito and are able to generate access tokens.

There are quite a few articles about Spring and OAuth. However, Spring Security advances fast and things get outdated quickly.

Since there are many good articles about OAuth/AWS Cognito Setup out there, I am going to get into the code right away.

Basic setup

Let’s quickly initialize a new project using the great Spring Initializr.

Spring Initializr

Again, we only want to verify the tokens sent to our application and make sure the user is authanticated and has the proper roles to execute a function.

We do not want to create custom login page or anything similar in this tutorial.

We need the following modules:

  • Spring-Security
  • Spring Web
  • OAuth2 Resource Server

To test the authorization, let us create a very simple controller:

Let’s configure spring, so we can verify tokens and make sure the user is authenticated.

You can find your cognito pool id under General Settings > Pool Id.

That’s it. Crazy right?

AWS Cognito provides informations about endpoints and public certificates under the URL https://cognito-idp.*aws-region*.amazonaws.com/*pool-id*/.well-known/openid-configuration#.

Spring will fetch all the necessary information needed to verify tokens on startup. The tokens are encrypted with an RSA signature with SHA-256. The public key is enough to verify the tokens are legit.

Let’s verify it is working.

When requesting the endpoint without any authorization, we should run into 401 unauthorized.

As mentioned earlier, I expect you to have a setup where you can get access tokens.

Tokens get verified and we can access the endpoint.

Check user groups

If you want to verify that a user is in a specific group, you need to configure a little bit to let Spring know how to extract the roles out of the Cognito json web tokens.

You can now get the assigned roles by accessing the security context holder:

If you want to be a able to annotate your methods to secure them like this:

You need to enable global method security.

That was pretty quick to setup right?

You can find the source on Github.

If you like this post, feel free to follow me or hit me up on Twitter.

Originally published at kevcodez.de.

--

--