AWS networking

AWS Cognito + Spring Complete Example


Amazon Cognito lets you add user sign-up, sign-in, and access control to your web and mobile apps quickly and easily.  With Cognito, you don't have to worry about user registration and login. In this example, we will integrate Spring boot with AWS Cognito.

1. Configure AWS Cognito.

Login to aws console and navigate to Cognito. https://aws.amazon.com/cognito/.

Create a user pool and configure it. Here I will mention some of the important points which are needed to run the example I have given.
Once the pool is created, create an app client.



After that, configure the app client. Note that I have run this app at localhost:8089. Call back and sign out URLs are from the same host and port.

Create a domain that will be used to configure the Spring application later.

2. Creating the Spring boot application.

I used the spring boot initializer to create the application. Make sure to add below dependencies when creating the application.

3. Cognito configuration

Add the following properties to your property file. Get the relevant information from the Cognito console.
Note the logout URL on the home page.

4. Finalization

There are more security configurations.
HttpSecurity.oauth2Login() provides a number of configuration options for customizing OAuth 2.0 Login. By default, the OAuth 2.0 Login Page is auto-generated but in this example, we are using a custom page. But you can see the auto-generated page in this URL; http://localhost:8089/login.

The default login page shows each configured OAuth Client with its ClientRegistration.clientName as a link. This link is capable of initiating the Authorization Request.

In this example, you can see that link in the home.html page.
<a class="button login is-primary" 
th:href="@{/oauth2/authorization/cognito-client-1}">
Log in with Amazon Cognito</a>

Few screens from the application.
Home page


Login page


Home page after login


Logout confirmation page

Download the code and try to run it. https://github.com/h-hub/aws-cognito-spring
It is the best way to learn.

@EnableOAuth2Sso can also be used to configure Spring to use OAuth2. We can implement it in the future. https://spring.io/guides/tutorials/spring-boot-oauth2/

References

  • https://docs.spring.io/spring-security/site/docs/5.0.7.RELEASE/reference/html/oauth2login-advanced.html
  • https://www.baeldung.com/spring-security-oauth-cognito
  • https://www.baeldung.com/spring-security-5-oauth2-login
  • https://aws.amazon.com/cognito/
  • https://docs.aws.amazon.com/cognito/latest/developerguide/getting-started-with-cognito-user-pools.html
  • https://spring.io/guides/tutorials/spring-boot-oauth2/


Comments