Spring Boot Security: Implementing OAuth2 Authentication with AWS Cognito


In today’s cloud-native applications, secure authentication and authorization are essential. AWS Cognito offers a scalable and fully managed identity provider, making it a great choice for integrating OAuth2 into your Spring Boot applications.
In this blog, we'll walk through how to implement OAuth2 authentication with AWS Cognito in a Spring Boot application using Spring Security.
🚀 Why AWS Cognito?
AWS Cognito handles user sign-up, sign-in, and access control with minimal effort. It supports:
Social identity providers (Google, Facebook)
SAML
Custom authentication flows
Integration with AWS IAM
🛠️ Prerequisites
Java 17+
Spring Boot (3.x preferred)
Maven or Gradle
AWS account with a configured Cognito User Pool
Basic knowledge of OAuth2 and Spring Security
🔐 Step 1: Set Up AWS Cognito User Pool
Go to AWS Console → Cognito → Create user pool.
Enable email or username-based sign-in.
Create a domain under the "App integration" section (e.g.,
your-app.auth.ap-south-1.amazoncognito.com
).Under “App Clients”:
Create a new app client.
Uncheck the “Generate client secret” (for web apps).
Set callback URL (e.g.,
http://localhost:8080/login/oauth2/code/cognito
)Set logout URL (e.g.,
http://localhost:8080
)Enable Authorization Code Grant.
Take note of:
User Pool ID
App client ID
Domain URL
Region
🧩 Step 2: Add Dependencies
In your pom.xml
(Maven):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
🧾 Step 3: Configure application.yml
spring:
security:
oauth2:
client:
registration:
cognito:
client-id: YOUR_APP_CLIENT_ID
client-name: Cognito
provider: cognito
authorization-grant-type: authorization_code
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
scope:
- email
- openid
- profile
provider:
cognito:
issuer-uri: https://cognito-idp.ap-south-1.amazonaws.com/YOUR_USER_POOL_ID
user-name-attribute: cognito:username
🛡️ Step 4: Configure Security
Create a file SecurityConfig.java
:
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/public").permitAll()
.anyRequest().authenticated()
)
.oauth2Login()
.and()
.logout()
.logoutSuccessUrl("/")
.invalidateHttpSession(true);
return http.build();
}
}
🧪 Step 5: Run and Test
Run your application.
Open
http://localhost:8080
.Click Login with Cognito.
You will be redirected to the Cognito-hosted login page.
After login, you'll be redirected back and authenticated.
📤 Bonus: Access User Info
To access user details in a controller:
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
@RestController
public class UserController {
@GetMapping("/user")
public String user(Principal principal) {
OidcUser user = (OidcUser) principal;
return "Hello, " + user.getFullName();
}
}
✅ Conclusion
Integrating AWS Cognito with Spring Boot via OAuth2 is straightforward and provides robust, scalable authentication. You don’t need to manage passwords, sessions, or social logins manually—Cognito handles it for you.
This setup can be further enhanced with role-based access, token customization, and integration with API Gateway or Lambda.
📚 Further Reading
Subscribe to my newsletter
Read articles from Jaya Vel Rajan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Jaya Vel Rajan
Jaya Vel Rajan
Welcome to the captivating world of data! Meet Jaya Vel Rajan(that's me!), an aspiring data analyst and passionate data science enthusiast. My insatiable curiosity fuels their exploration of the power of data. Through my captivating blog, I share my knowledge in a unique and accessible way, making complex concepts a breeze. Join me on this thrilling journey, uncovering insights and shaping the future of data. Follow my blog for inspiring, informative, and dazzling content that will leave you amazed by the boundless possibilities of data! 🌟📊✨