Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

FastAPI
  • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  • RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Backend vs Frontend: What Runs Where, and Why the Server Is the One You Trust
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
  • Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes
  • POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
  • Paging, Sorting and Filtering a REST API in FastAPI
  • File Upload and Download in FastAPI: multipart, UploadFile and FileResponse
  • API Versioning in FastAPI with an API-Version Header
  • Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat
  • A FastAPI REST API End to End: One App Visit, Seven Requests
  • The Book API in FastAPI: A Contract a React Client Can Rely On
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Dependency Injection With FastAPI Depends: Providers, dependency_overrides and yield
  • A Layered FastAPI Project: Controllers, Services, Schemas and One Folder per Concern
  • FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
  • FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
  • Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
  • FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
  • From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
  • Docker Compose: Run a FastAPI App and Postgres From One File
  • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
  • Repository and Unit of Work With SQLAlchemy: Both Writes or Neither, and a Test With No Database
  • How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
  • An Auth Starter Kit with Keycloak: Build Sign In Once, Put the Backend Between React and the Identity Provider
  • Protecting a Python API with Keycloak: Check the JWT Signature, Issuer and Expiry in FastAPI, Django and Flask
  • How an Identity Provider Login Works: The OpenID Connect Code Flow vs a Backend Password Grant, with Keycloak
  • AWS Cognito vs Keycloak: User Pools, App Clients and When a Managed Identity Provider Wins
  • Migrating FastAPI from Keycloak to AWS Cognito: The Four Values, the JWKS Address and Every Check on an Access Token
  • Testing a Cognito Login End to End: Allow the Password Flow, Confirm the Email Code, and Reset a Forgotten Password
  • Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
  • Testing a FastAPI Blog with pytest: a Test Database through dependency_overrides, Login Fixtures and Reading a Failure
  • Smoke-Testing a Dockerized LLM App by Hand: Stage the Weights, Check Every Layer, Make Errors Say Why
  1. Blog
  2. /
  3. FastAPI
  4. /
  5. Authentication

Testing a Cognito Login End to End: Allow the Password Flow, Confirm the Email Code, and Reset a Forgotten Password

Sign up, confirm, log in and reset a password against a real Cognito pool, fixing each error where it shows up: the password auth flow switched off on the app client, an unconfirmed user, a Next.js build that fails on useSearchParams, and a missing forgot password flow.

Chaand Sheikh

·27 November 2026·Updated 29 November 2026Authentication

What you will learn

  • Fix 'USER_PASSWORD_AUTH flow not enabled for this client' on the app client
  • Keep auto confirm off and add confirm and resend-code endpoints
  • Add forgot password and reset password with Cognito's own codes
  • Read Cognito errors and build logs as the instructions for the next fix

Before you start

  • Migrating FastAPI from Keycloak to AWS Cognito

The login has moved from Keycloak to Amazon Cognito. Now it's time to test it end to end: sign up, confirm the email, log in, and reset a forgotten password, fixing each error right where it shows up.

One setting first: auto confirm stays off

The last line of sample.env is COGNITO_AUTO_CONFIRM_SIGN_UP=false. If it were true, the backend would confirm every new user itself, without checking the email:

            response = get_cognito_client().sign_up(**kwargs)
            confirmed = bool(response.get("UserConfirmed"))
            if settings.cognito_auto_confirm_sign_up and not confirmed:
                get_cognito_client().admin_confirm_sign_up(
                    UserPoolId=settings.cognito_user_pool_id,
                    Username=email,
                )

That's a security hole, because anyone could sign up with an email address they don't own. So keep it false. Then docker compose up --build starts the front end on port 3000 and the FastAPI backend on port 8000.

Error 1: the password flow isn't allowed

Open the app, click log in, type an email and password. The first answer:

USER_PASSWORD_AUTH flow not enabled for this client

The backend signs users in by sending the username and password straight to Cognito with initiate_auth. Cognito accepts that only when the app client allows this flow. In the console: Amazon Cognito, your user pool, app clients, your client, the authentication flows card, edit. "Sign in with username and password: ALLOW_USER_PASSWORD_AUTH" is not ticked. Tick it and save. The banner says the app client was updated, and username and password now shows under authentication flows.

Log in again with an account that doesn't exist, and you get "Invalid username or password". That's a normal error. It means the flow works and Cognito is checking the credentials.

Error 2: the user isn't confirmed

Sign up with an email and a password. The app says the user is registered but must be confirmed before it can log in. In the console under users, the new user shows email verified "No" and confirmation status "Unconfirmed".

Who sends the code? Under authentication methods, email says "send email with Cognito", from Cognito's default no-reply sender. It's fine for testing, but because it isn't your own domain, the mail usually lands in spam. And it did: subject "Your verification code", code inside.

Now log in with this user:

User is not confirmed. Confirm the account before logging in.

Cognito is doing its job. The gap is in the app: it can register a user, but there's no page to type the code. The backend already turns Cognito's UserNotConfirmedException into a 403 with that message. So the coding agent got a plain prompt: paste the error, and say that we can register the user but can't confirm it, so change the logic so the user can confirm and then log in. It read the project, planned two endpoints and a page, and added:

@router.post(
    "/confirm",
    response_model=ConfirmSignupResponse,
    summary="Confirm a newly registered user with the emailed code",
)
async def confirm(body: ConfirmSignupRequest) -> ConfirmSignupResponse:
    await cognito_client.confirm_sign_up(email=body.email, code=body.code)
    return ConfirmSignupResponse()


@router.post(
    "/resend-confirmation",
    response_model=ResendCodeResponse,
    summary="Resend the Cognito confirmation code to the user's email",
)
async def resend_confirmation(body: ResendCodeRequest) -> ResendCodeResponse:
    await cognito_client.resend_confirmation_code(email=body.email)
    return ResendCodeResponse()

Behind /auth/confirm is Cognito's confirm_sign_up, with the secret hash because the client has a secret:

    async def confirm_sign_up(email: str, code: str) -> None:
        kwargs: dict[str, Any] = {
            "ClientId": settings.cognito_app_client_id,
            "Username": email,
            "ConfirmationCode": code,
        }
        secret_hash = _secret_hash(email)
        if secret_hash:
            kwargs["SecretHash"] = secret_hash

        try:
            get_cognito_client().confirm_sign_up(**kwargs)
        except ClientError as exc:
            raise _map_cognito_error(exc, "Could not confirm user") from exc

On the front end, the login page now catches that 403 and sends the user to the confirm page:

      if (err instanceof ApiError && err.status === 403 && /confirm/i.test(err.message)) {
        const params = new URLSearchParams({ email });
        router.replace(`/confirm?${params.toString()}`);
        return;
      }

Error 3: the build fails

Rebuild, and the front end fails: "failed to solve: npm run build, exit code 1". An old cached image sometimes gets in the way, so docker system prune -a (it removes images not in use, after you type y) rules that out. The fresh build failed in the same place, so the cache wasn't the problem. The log said "Error occurred prerendering page /confirm".

The fix took no prompt at all: copy the whole stack trace and paste it to the agent. It found the cause. In Next.js, a page that reads useSearchParams has to be wrapped in a Suspense boundary. It fixed the confirm page and the login page:

export default function LoginPage() {
  return (
    <>
      <section className="flex flex-1 items-center justify-center">
        <Suspense fallback={<div className="w-full max-w-sm" />}>
          <LoginForm />
        </Suspense>
      </section>

Now log in with the unconfirmed user and the app opens "Confirm your email", with a code field, a confirm account button and a link to resend the code. Type the code, confirm, log in: "Signed in as" the user, and the dashboard. The resend link works too. Ask twice and two codes arrive; use the newest.

Gap 4: no way back after a forgotten password

One more plain-line prompt: as of now there's no way to recover the password, so implement the forgot password functionality. It added two endpoints backed by Cognito's forgot_password and confirm_forgot_password:

    async def confirm_forgot_password(
        email: str, code: str, new_password: str
    ) -> None:
        kwargs: dict[str, Any] = {
            "ClientId": settings.cognito_app_client_id,
            "Username": email,
            "ConfirmationCode": code,
            "Password": new_password,
        }
        secret_hash = _secret_hash(email)
        if secret_hash:
            kwargs["SecretHash"] = secret_hash

        try:
            get_cognito_client().confirm_forgot_password(**kwargs)
        except ClientError as exc:
            raise _map_cognito_error(exc, "Could not reset password") from exc

From login: forgot password, enter the email, Cognito emails a code, enter the code and a new password on the reset page, and you're back at login. Log in with the new password and My Projects opens.

What happens behind the scenes

Sign up, confirm, login and reset through the backend Next.js page FastAPI Cognito sign up /auth/register user UNCONFIRMED, emails code confirm page /auth/confirm confirm_sign_up: CONFIRMED log in /auth/login USER_PASSWORD_AUTH: tokens forgot password /auth/forgot-password emails a reset code reset page /auth/reset-password confirm_forgot_password
The browser only talks to the app. The pages call FastAPI, and FastAPI calls Cognito for every step.

Notice how much Cognito does here. The codes, the emails, the confirmation and the password reset are all built in. With Keycloak you'd set up the mail server and switch these flows on yourself.

Common mistakes

  • Turning auto confirm on to "make the error go away". It lets anyone claim any email.
  • Leaving ALLOW_USER_PASSWORD_AUTH off on the app client when the backend uses USER_PASSWORD_AUTH.
  • Pruning Docker and rebuilding over and over. Read the stack trace first; it named the page.
  • Shipping with Cognito's default sender. Expect the codes to land in spam.

Quick recap

  • Keep auto confirm off, and allow the username and password flow on the app client.
  • When an error comes from Cognito, read it: it usually names the setting to change.
  • When a build fails, paste the stack trace to the agent.
  • Confirm, resend, forgot and reset are four small endpoints over Cognito calls, each with the secret hash.

Keep going in FastAPI · 36 of 39

Previous
Migrating FastAPI from Keycloak to AWS Cognito: The Four Values, the JWKS Address and Every Check on an Access Token
Next post
Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def

Follow GET / through the FastAPI blog to two SQL statements and an HTML page, then a login: one SELECT, a bcrypt check, a 303 with a signed session cookie that decodes to user_id 1. A changed cookie gets 401, a plain user 403, and three slow requests on async def with a blocking session finish at 1.92 s while a ping waits 1.83 s.

An Auth Starter Kit with Keycloak: Build Sign In Once, Put the Backend Between React and the Identity Provider

Almost every project needs sign in, sign out and a token check, so build them once in a starter kit. Tour the kit's four pillars, then finish it: a fix prompt, a backend that sits between React and Keycloak with register, login, me and logout routes, and the limits of a stateless access token.

Protecting a Python API with Keycloak: Check the JWT Signature, Issuer and Expiry in FastAPI, Django and Flask

Keycloak signs the access token; your API only checks it. Run Keycloak in Docker with a realm file, fetch its public keys once, check RS256, the issuer and the expiry, and protect /api/me with one Depends. Then the same check as a Django REST framework class and a Flask decorator.

How an Identity Provider Login Works: The OpenID Connect Code Flow vs a Backend Password Grant, with Keycloak

What an identity provider does, the four Keycloak words you see everywhere, the standard OpenID Connect sign in (redirect, code, token), and the custom-page version where FastAPI sends a password grant. Then one token followed from login to the check, plus refresh, logout and dev mode.

On this page

  • One setting first: auto confirm stays off
  • Error 1: the password flow isn't allowed
  • Error 2: the user isn't confirmed
  • Error 3: the build fails
  • Gap 4: no way back after a forgotten password
  • What happens behind the scenes
  • Common mistakes
  • Quick recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.