AWS Cognito Federated Authentication with Google & SST
Managing user identities is a critical part of modern application development. Instead of handling usernames and passwords yourself, offloading this to a trusted provider like Google via AWS Cognito Federated Authentication is a secure and user-friendly approach.
In this guide, we'll walk through setting up Google as an Identity Provider (IdP) for an AWS Cognito User Pool using Infrastructure as Code (IaC) with SST (Serverless Stack) and Pulumi.
<div class="toc"> <ul> <li><a href="#prerequisites">Prerequisites</a></li> <li><a href="#setting-up-google-oauth">Step 1: Setting up Google OAuth</a></li> <li><a href="#creating-cognito-resources">Step 2: Creating Cognito Resources with SST</a></li> <li><a href="#connecting-google-idp">Step 3: Connecting Google as an IdP</a></li> <li><a href="#frontend-integration">Step 4: Frontend Integration</a></li> <li><a href="#conclusion">Conclusion</a></li> <li><a href="#faq">FAQ</a></li> </ul> </div>Prerequisites <a id="prerequisites"></a>
Before we dive in, ensure you have the following:
- An AWS Account.
- A Google Cloud Project.
- Node.js and SST installed.
Step 1: Setting up Google OAuth <a id="setting-up-google-oauth"></a>
First, we need to configure Google to allow our application to use it for authentication.
- Create a Project: Go to the Google Cloud Console and create a new project.
- Consent Screen: Navigate to APIs & Services > OAuth consent screen.
- Choose External user type.
- Fill in the App Name, User Support Email, and Developer Contact Information.
- You don't need to add scopes for basic login yet.
- Create OAuth Client: Go to Credentials > Create Credentials > OAuth client ID.
- Application type: Web application.
- Authorized JavaScript origins: Add
http://localhost:3000(for development). - Authorized redirect URIs: This is crucial. It follows the pattern:
https://<your-domain>.auth.<region>.amazoncognito.com/oauth2/idpresponseNote: We will define this domain in the next step, so keep this tab open to update it later.
After creation, copy your Client ID and Client Secret. You'll need these for your .env file.
Step 2: Creating Cognito Resources with SST <a id="creating-cognito-resources"></a>
We'll use SST (which leverages Pulumi) to define our infrastructure. This ensures our setup is reproducible.
Defining the User Pool
First, create the Cognito User Pool. We only want to allow sign-ins via Google, so we can restrict the password policy and auto-verified attributes.
const userPool = new aws.cognito.UserPool('identity-pool', {
passwordPolicy: {
minimumLength: 8,
requireLowercase: false,
requireNumbers: false,
requireSymbols: false,
requireUppercase: false,
},
autoVerifiedAttributes: ['email'],
});
Setting up the Domain
Cognito needs a domain to host the login UI and handle redirects.
new aws.cognito.UserPoolDomain('user-pool-domain', {
domain: process.env.COGNITO_USER_POOL_DOMAIN, // e.g., my-app-auth
userPoolId: userPool.id,
});
Important: Go back to your Google Console and update the Authorized redirect URI with this domain.
Step 3: Connecting Google as an IdP <a id="connecting-google-idp"></a>
Now, we link Google to our User Pool. We map Google's email and sub (subject) claims to Cognito's email and username.
const idpGoogle = new aws.cognito.IdentityProvider('idp-google', {
userPoolId: userPool.id,
providerName: 'Google',
providerType: 'Google',
providerDetails: {
client_id: process.env.GOOGLE_OAUTH_CLIENT_ID,
client_secret: process.env.GOOGLE_OAUTH_CLIENT_SECRET,
authorize_scopes: 'openid profile email',
},
attributeMapping: {
email: 'email',
username: 'sub',
},
});
Finally, create the User Pool Client that your frontend will use.
const userPoolClient = new aws.cognito.UserPoolClient('user-pool-client', {
userPoolId: userPool.id,
allowedOauthFlows: ['code'],
allowedOauthScopes: ['email', 'openid', 'profile'],
supportedIdentityProviders: [idpGoogle.providerName],
callbackUrls: ['http://localhost:3000/auth'], // Your frontend callback
logoutUrls: ['http://localhost:3000'],
});
Step 4: Frontend Integration <a id="frontend-integration"></a>
To connect your Next.js frontend, you can use the sst.aws.Nextjs construct to pass environment variables automatically.
new sst.aws.Nextjs('frontend', {
environment: {
NEXT_PUBLIC_COGNITO_CLIENT_ID: userPoolClient.id,
NEXT_PUBLIC_COGNITO_DOMAIN: `https://${process.env.COGNITO_USER_POOL_DOMAIN}.auth.${aws.config.region}.amazoncognito.com`,
},
});
In your frontend application, you can now construct the login URL:
const loginUrl = `${process.env.NEXT_PUBLIC_COGNITO_DOMAIN}/login?client_id=${process.env.NEXT_PUBLIC_COGNITO_CLIENT_ID}&response_type=code&scope=email+openid+profile&redirect_uri=http://localhost:3000/auth`;
Redirecting the user to this URL will start the Google OAuth flow.
Conclusion <a id="conclusion"></a>
By integrating Google with AWS Cognito, you simplify the login process for users and improve security by not handling passwords directly. Using SST and Pulumi allows you to manage this infrastructure as code, making it easy to deploy and maintain.
FAQ <a id="faq"></a>
Q: Can I use other providers like Facebook or Apple? A: Yes, Cognito supports multiple identity providers including Facebook, Amazon, Apple, and generic OIDC/SAML providers.
Q: Is the Hosted UI required? A: While not strictly required if you implement the OAuth flow manually, Cognito's Hosted UI provides the easiest way to handle the federation redirects.
Q: How do I handle token refreshing? A: Cognito returns a refresh token. Your application (or a library like AWS Amplify) can use this token to get new access tokens without forcing the user to log in again.
<script type="application/ld+json"> { "@context": "https://schema.org", "@type": "Article", "headline": "AWS Cognito Federated Authentication with Google & SST", "description": "Step-by-step guide to implementing AWS Cognito Federated Authentication with Google using SST and Pulumi.", "author": { "@type": "Organization", "name": "DevOpsN" }, "publisher": { "@type": "Organization", "name": "DevOpsN", "logo": { "@type": "ImageObject", "url": "https://[EN_DOMAIN]/logo.png" } }, "datePublished": "2025-10-25" } </script> <script type="application/ld+json"> { "@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [{ "@type": "Question", "name": "Can I use other providers like Facebook or Apple?", "acceptedAnswer": { "@type": "Answer", "text": "Yes, Cognito supports multiple identity providers including Facebook, Amazon, Apple, and generic OIDC/SAML providers." } }, { "@type": "Question", "name": "Is the Hosted UI required?", "acceptedAnswer": { "@type": "Answer", "text": "While not strictly required if you implement the OAuth flow manually, Cognito's Hosted UI provides the easiest way to handle the federation redirects." } }, { "@type": "Question", "name": "How do I handle token refreshing?", "acceptedAnswer": { "@type": "Answer", "text": "Cognito returns a refresh token. Your application (or a library like AWS Amplify) can use this token to get new access tokens without forcing the user to log in again." } }] } </script>Image Suggestions
- Google OAuth Consent Screen: Screenshot of the Google Cloud Console showing the configuration of the OAuth consent screen. Alt text: "Google Cloud Console OAuth consent screen configuration".
- Cognito Identity Provider Settings: Screenshot of AWS Cognito console showing Google configured as an IdP. Alt text: "AWS Cognito Identity Provider settings for Google".
- Authentication Flow Diagram: A simple diagram showing User -> Next.js App -> Cognito -> Google. Alt text: "AWS Cognito Federated Authentication flow diagram".
Link Suggestions
- Internal: AWS Consultancy
- Internal: Kubernetes Consultancy
- Internal: Home
- External: AWS Cognito Documentation
- External: Google Identity Platform
Kaynak / Source: https://awsfundamentals.com/blog/cognito-federated-auth