Amazon Cognito with Spring Boot JWT Authentication
Learn how to integrate Amazon Cognito with Spring Boot using JWT authentication. This guide covers User Pools, Identity Pools, OAuth2, JWT validation, Spring Security Resource Server, social login, refresh tokens, role-based authorization, and production best practices.
Introduction
Authentication and authorization are fundamental requirements for modern applications.
Whether you're building:
- REST APIs
- Mobile Applications
- React Applications
- Angular Applications
- Microservices
- SaaS Platforms
you need a secure way to:
- Register users
- Authenticate users
- Generate JWT tokens
- Validate access tokens
- Manage user roles
- Support Google and GitHub login
- Secure Spring Boot APIs
Instead of building authentication from scratch, AWS provides Amazon Cognito, a fully managed identity service.
In this article, we will integrate Amazon Cognito with Spring Boot using JWT authentication and Spring Security.
Learning Objectives
After completing this article, you will understand:
- What is Amazon Cognito?
- User Pools
- Identity Pools
- JWT Authentication
- OAuth2 Authorization Code Flow
- Access Token
- ID Token
- Refresh Token
- Spring Security Integration
- JWT Validation
- Social Login
- Role-Based Authorization
- Production Best Practices
Why Cognito?
Without Cognito:
Client
│
▼
Spring Boot
│
Custom Login
│
Database
Problems:
- Build authentication yourself
- Password hashing
- MFA
- Password reset
- Token generation
- Social login
- Security vulnerabilities
With Cognito:
Client
↓
Amazon Cognito
↓
JWT Token
↓
Spring Boot API
Benefits:
- Managed authentication
- JWT support
- OAuth2/OpenID Connect
- MFA
- Social Login
- Secure user management
What is Amazon Cognito?
Amazon Cognito is AWS's managed authentication service.
It provides:
- User Registration
- User Login
- OAuth2
- OpenID Connect
- JWT Tokens
- MFA
- Password Reset
- Social Login
- Device Tracking
Cognito Components
| Component | Purpose |
|---|---|
| User Pool | User Authentication |
| Identity Pool | AWS Resource Access |
| App Client | OAuth Client |
| Hosted UI | Login Page |
| JWT | Authentication Token |
High-Level Architecture
flowchart LR
USER[React / Mobile App]
COGNITO[Amazon Cognito]
JWT[JWT Token]
SPRING[Spring Boot API]
USER --> COGNITO
COGNITO --> JWT
JWT --> SPRING
Enterprise Architecture
flowchart TD
Users
CloudFront
AWSWAF
Cognito
API_Gateway
SpringBoot
Aurora
Users --> CloudFront
CloudFront --> AWSWAF
AWSWAF --> Cognito
Cognito --> API_Gateway
API_Gateway --> SpringBoot
SpringBoot --> Aurora
Authentication Flow
flowchart LR
User
Login
Cognito
JWT
SpringBoot
User --> Login
Login --> Cognito
Cognito --> JWT
JWT --> SpringBoot
Authorization Flow
Login
↓
JWT Token
↓
API Request
↓
Token Validation
↓
Authorized
User Pool
User Pool manages:
- User accounts
- Passwords
- MFA
- Groups
- JWT Tokens
Think of it as your application's user database.
Identity Pool
Identity Pool provides temporary AWS credentials.
Useful when users need access to:
- S3
- DynamoDB
- AppSync
Identity Pools are optional for many backend APIs.
JWT Tokens
Cognito generates three tokens.
ID Token
Contains:
- User ID
- Username
- Claims
Used by the client application.
Access Token
Used to access protected APIs.
Spring Boot validates this token.
Refresh Token
Used to obtain a new Access Token without requiring the user to log in again.
JWT Structure
Header
↓
Payload
↓
Signature
Example:
xxxxx.yyyyy.zzzzz
OAuth2 Authorization Code Flow
flowchart LR
Browser
Cognito
AuthorizationCode
JWT
SpringBoot
Browser --> Cognito
Cognito --> AuthorizationCode
AuthorizationCode --> JWT
JWT --> SpringBoot
Recommended for:
- React
- Angular
- Next.js
- Mobile Apps
Real-Time Use Cases
Amazon Cognito is commonly used for:
- Banking Portals
- Healthcare Applications
- SaaS Products
- Mobile Applications
- Enterprise APIs
- E-Commerce Platforms
Step 1 Create User Pool
AWS Console
↓
Amazon Cognito
↓
Create User Pool
Pool Name
codewithvenu-users
Step 2 Configure Login
Enable
- Username
Users can log in using either identifier.
Step 3 Password Policy
Example
Minimum
8 Characters
Require
- Uppercase
- Lowercase
- Number
- Special Character
Step 4 Create App Client
Choose
Public Client
Enable
Authorization Code Flow
Step 5 Configure Callback URL
Example
http://localhost:3000/login/oauth2/code/cognito
Production
https://codewithvenu.com/login/oauth2/code/cognito
Step 6 Enable Hosted UI
Amazon Cognito provides a hosted login page.
Example
https://codewithvenu.auth.us-east-1.amazoncognito.com/login
Step 7 Enable Social Login
Supported providers:
- GitHub
- Apple
- Microsoft
Users can authenticate without creating a new password.
Step 8 Spring Boot Dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
Step 9 application.yml
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://cognito-idp.us-east-1.amazonaws.com/us-east-1_ABC123XYZ
Spring Security automatically downloads the JSON Web Key Set (JWKS) from the issuer to validate Cognito JWT signatures.
JWT Validation Flow
flowchart LR
Client
JWT
SpringSecurity
Cognito
Client --> JWT
JWT --> SpringSecurity
SpringSecurity --> Cognito
Security Configuration
@Bean
SecurityFilterChain security(HttpSecurity http)
throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth ->
oauth.jwt());
return http.build();
}
Public API
GET
/public/health
No authentication required.
Protected API
GET
/api/orders
Requires:
Authorization:
Bearer JWT_TOKEN
Sample JWT Request
GET /api/orders
Authorization:
Bearer eyJhbGciOi...
JWT Claims
Example
{
"sub":"12345",
"email":"[email protected]",
"scope":"openid profile",
"groups":[
"ADMIN"
]
}
Role-Based Authorization
Example
@PreAuthorize("hasRole('ADMIN')")
Only administrators can access the endpoint.
Refresh Token Flow
flowchart LR
ExpiredToken
RefreshToken
Cognito
NewAccessToken
ExpiredToken --> RefreshToken
RefreshToken --> Cognito
Cognito --> NewAccessToken
Logout Flow
User
↓
Logout
↓
Invalidate Session
↓
Remove Tokens
Multi-Factor Authentication
Enable:
- SMS OTP
- TOTP Authenticator Apps
- Email Verification
Recommended for production systems.
Monitoring
Monitor:
- Sign-in failures
- Successful logins
- MFA usage
- Token requests
- OAuth errors
Use:
- CloudWatch
- CloudTrail
Common Errors
401 Unauthorized
Verify:
- Access Token
- Expiration
- Authorization Header
Invalid JWT
Check:
- Issuer URI
- Audience
- Token Signature
CORS Error
Configure:
- Allowed Origins
- Allowed Methods
- Allowed Headers
Redirect URI Mismatch
Verify callback URLs configured in the Cognito App Client.
Production Architecture
flowchart TD
Users
Route53
CloudFront
AWSWAF
Cognito
API_Gateway
SpringBootAZ1
SpringBootAZ2
Aurora
CloudWatch
Users --> Route53
Route53 --> CloudFront
CloudFront --> AWSWAF
AWSWAF --> Cognito
Cognito --> API_Gateway
API_Gateway --> SpringBootAZ1
API_Gateway --> SpringBootAZ2
SpringBootAZ1 --> Aurora
SpringBootAZ2 --> Aurora
SpringBootAZ1 --> CloudWatch
SpringBootAZ2 --> CloudWatch
Best Practices
- Use Authorization Code Flow
- Always use HTTPS
- Enable MFA
- Validate JWTs using Spring Security
- Protect APIs with API Gateway
- Keep JWT expiration short
- Use Refresh Tokens securely
- Enable CloudTrail auditing
- Assign users to Cognito Groups
- Use Role-Based Authorization
- Avoid storing sensitive data in JWT claims
- Monitor authentication metrics
Developer Checklist
Before production deployment:
- User Pool created
- App Client configured
- Hosted UI enabled (optional)
- Callback URLs configured
- OAuth2 enabled
- JWT validation configured
- Spring Security integrated
- MFA enabled
- Social login configured (if required)
- HTTPS enabled
- CloudWatch monitoring enabled
Interview Questions
What is Amazon Cognito?
Amazon Cognito is a managed authentication and user identity service that supports OAuth2, OpenID Connect, JWT tokens, social login, and MFA.
What is the difference between User Pools and Identity Pools?
| User Pool | Identity Pool |
|---|---|
| Authentication | AWS Resource Access |
| Stores users | Provides temporary AWS credentials |
| Issues JWTs | Maps authenticated identities to IAM roles |
What are the three JWT tokens returned by Cognito?
- ID Token
- Access Token
- Refresh Token
Why use Spring Security Resource Server?
It automatically validates JWT signatures, expiration, issuer, and claims for protected APIs.
Can Amazon Cognito support Google and GitHub login?
Yes. Cognito can federate identities from providers such as Google, GitHub, Apple, Facebook, and Microsoft using standard OAuth2/OpenID Connect flows.
What is the recommended OAuth2 flow for web applications?
Authorization Code Flow with PKCE for browser-based applications.
Summary
In this article, we integrated Amazon Cognito with Spring Boot using JWT authentication.
We covered:
- Amazon Cognito fundamentals
- User Pools
- Identity Pools
- JWT tokens
- OAuth2 Authorization Code Flow
- Spring Security Resource Server
- JWT validation
- Role-based authorization
- Refresh tokens
- Social login
- MFA
- Production best practices
Amazon Cognito provides a secure, scalable authentication solution for Spring Boot applications while eliminating the need to build and maintain custom authentication infrastructure. Combined with Spring Security, API Gateway, and AWS WAF, it forms a robust security foundation for modern cloud-native applications.
Comments
Share a question, correction, or practical insight about this article.
Checking login status...
Loading approved comments...