AWS AppRunner: Redirect URI Mismatch Error with Amazon Cognito

29 Views Asked by At

I'm building a Next.js application with Google Sign-In using AWS Cognito. It works perfectly on localhost, but I encounter a redirect URI mismatch error when deployed to production. I've confirmed that the callback URL is correctly configured in Cognito.

Client-Side Code (google-sign-in/route.js):

import { NextRequest, NextResponse } from "next/server";
import crypto from 'crypto'
import Cognito from "next-auth/providers/cognito";

const {
    COGNITO_DOMAIN,
    COGNITO_CLIENT_ID
} = process.env


console.log(COGNITO_CLIENT_ID)

export async function GET(request) {
    let authorizeParams = new URLSearchParams()
    const origin = request.nextUrl.origin
    console.log(origin)

    const state = crypto.randomBytes(16).toString('hex')

    authorizeParams.append('response_type', 'code')
    authorizeParams.append('client_id', COGNITO_CLIENT_ID)
    authorizeParams.append('redirect_uri', `${origin}/api/auth/callback`)
    authorizeParams.append('state', state)
    authorizeParams.append('identity_provider', 'Google')
    authorizeParams.append('scope', 'profile email openid')


    return NextResponse.redirect(`${COGNITO_DOMAIN}/oauth2/authorize?${authorizeParams.toString()}`)
}   

Cognito Configuration:

[Cognito Allowed callbackUrl](https://i.stack.imgur.com/PxanR.png)

Callback code (api/auth/callback/route.js) :

import { NextResponse, NextRequest } from "next/server";
import {cookies} from 'next/headers'

const {
    COGNITO_DOMAIN,
    COGNITO_CLIENT_ID,
    COGNITO_CLIENT_SECRET
} = process.env

export async function GET(NextRequest) {
    try {
        const origin = NextRequest.nextUrl.origin
        const searchParams = NextRequest.nextUrl.searchParams
        const code = searchParams.get('code')

        console.log(code)
        if(!code) {
            const error = searchParams.get('error')
            return NextResponse.json({error: error || "Unknown error"})
        }

        const authorizationHeader = `Basic ${Buffer.from(`${COGNITO_CLIENT_ID}:${COGNITO_CLIENT_SECRET}`).toString('base64')}`
        
        const requestBody = new URLSearchParams({
            grant_type: 'authorization_code',
            client_id: COGNITO_CLIENT_ID,
            code: code,
            redirect_uri: `${origin}/api/auth/callback`
        })

        // Get tokens
        const res = await fetch(`${COGNITO_DOMAIN}/oauth2/token`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': authorizationHeader
            },
            body: requestBody
        })

        const data = await res.json()
        console.log(data)

        if (!res.ok) {
            return NextResponse.json({
                error: data.error,
                error_description: data.error_description
            })
        }

        // Store tokens in cookies
        const cookieStore = cookies()
        cookieStore.set('id_token', data.id_token)
        cookieStore.set('access_token', data.access_token)
        cookieStore.set('refresh_token', data.refresh_token)

        return NextResponse.redirect(new URL('/', NextRequest.nextUrl))
        
    } catch (error) {
        console.log("error")
        return NextResponse.json({ error: error })
    }
}

Output

The error while clicking on the signup with Google Output Screen

0

There are 0 best solutions below