Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Use Cypress to test Cognito authentication in two different ways: drive the Cognito sign-in page with cy.origin() when redirects and the login interaction are part of the test, or authenticate through your application’s auth library when the test is about behavior after sign-in. These approaches cover different things; a programmatic setup does not, by itself, test the hosted sign-in flow or its OAuth authorization-code and PKCE exchange.

For reliable coverage, keep at least one test of the actual login journey when it matters to your application, then use intentional session reuse or programmatic authentication for tests focused on authenticated features. Make your assertions reflect how your app and its protected services actually handle Cognito tokens.

Choose the authentication path that matches the test

Before writing Cypress commands, decide what behavior the test must prove. Cognito authentication is not just a form submission: an app may redirect to a Cognito-managed page, return to the app, store user-pool tokens, and use those tokens when a protected page or API is accessed. A test that skips one of those steps cannot establish that the skipped behavior works.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Approach Best suited to What it does not automatically cover
Browser-driven sign-in with cy.origin() The redirect to Cognito, visible sign-in interaction, and return to the app Every possible challenge or identity-provider configuration; those need tests for the configured flow
Programmatic authentication through the app’s auth library Tests of authenticated application behavior where logging in is setup rather than the subject The hosted sign-in page, browser redirect, and authorization-code/PKCE path

These are complementary strategies, not competing definitions of a valid test. A suite can use an end-to-end login test to cover authentication itself and establish authenticated state more directly for tests whose purpose is a dashboard, account setting, or protected operation.

#1 Best Overall
Thetis FIDO2 Security Key (USB-A, 2-Pack) - Hardware MFA & Passkey Access for Business, School ERP & Employee Accounts | Compatible with Windows, Google Workspace, Apple ID, Coinbase, Salesforce
  • FIDO2 & Passkey Ready: Business-ready and FIDO2 L1 certified. This key is supported by major management suites and is ideal for both individual and enterprise deployment. Works seamlessly with Gmail, Facebook, GitHub, Dropbox, Coinbase, and more.
  • Universal Connectivity (USB-A ): Features a built-in USB-A connector—simply unfold the key and plug it into your compatible PC or laptop for seamless authentication on the go.
  • Dedicated Manager App: Use the Thetis Manager App for the initial hardware PIN setup. Setting the PIN on the device first ensures a smooth registration process. Once the PIN is configured, you can begin registering the key across your favorite FIDO2-compatible online services.
  • Ultra-Durable & Portable: Featuring a rotating metal cover, this key is water, crush, and tamper-resistant. It fits easily on a keychain and requires no batteries or network connectivity.
  • Check FIDO2 compatibility before purchase - Known limitations: ID Austria is not supported (requires FIDO2 Level 2). Windows Hello login only works with Windows Enterprise editions that support Entra ID, and NFC is NOT supported.

Prepare Cognito and Cypress test configuration

Use a controlled test environment

Use a Cognito user pool and application configuration appropriate to the test environment, together with dedicated test users and predictable application data. Avoid using personal or production credentials. Keep passwords, client configuration, and other secrets out of source control; supply sensitive values through your CI secret store or local environment configuration.

Cypress’s Cognito example provisions resources for its sample application using Amplify CLI and reads configuration and credentials from environment variables. Those file names and provisioning commands are specific to that sample, not universal Cognito setup steps. Use your project’s established provisioning method and application configuration rather than copying sample infrastructure instructions as though every app needs them.

Check the enabled sign-in flow first

The Cognito app-client configuration determines which authentication flows the application can use. Inventory the flows your application actually enables before creating fixtures or selectors. Password sign-in, email or SMS one-time-password challenges, passkeys, and external identity providers do not all produce the same browser journey.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Cognito managed login provides user-facing pages for core user-pool operations, including password management, MFA, and attribute verification. The browser may therefore encounter a challenge or verification step after the initial credentials are submitted. A password-only test user cannot stand in for coverage of a flow that requires a one-time code, passkey, or external identity provider.

Test the hosted sign-in journey with cy.origin()

Use browser-driven login when the application’s redirect and the user-facing Cognito flow are part of the risk you need to cover. Cypress changes origin when the test visits Cognito, so commands that interact with the Cognito page belong inside cy.origin(). After the sign-in completes, assert that the browser returns to the application and that the expected authenticated behavior is available.

Configure the test inputs

Set the Cognito sign-in URL, application URL, and test credentials for the environment where Cypress runs. The following example expects Cypress environment values named cognitoUrl, appUrl, testEmail, and testPassword. Set cognitoUrl to the origin that actually serves your app’s Cognito login page, and adapt the form selectors and post-login assertion to your application.

Rank #2
FIDO2 Security Key [Folding Design] Thetis Universal Two Factor Authentication USB (Type A) for Multi-Layered Protection (HOTP) in Windows/Linux/Mac OS,Gmail,Facebook,Dropbox,SalesForce,GitHub
  • Passwordless World - A revolutionary new way to protect your account info. By being FIDO2 certified by the world’s largest ecosystem for standard-based, interoperable authentication, FIDO2 makes everyday log-in experience effortless and passwordless yet more secure than generic password style security. **Note: FIDO2 does NOT support Mac log-in.
  • Online Account Protection - FIDO2 key is backward compatible with U2F protocol and works with the newest Chrome browser with operating systems such as: Windows, macOS, or Linux. U2F can be supported and protected on all websites that follow U2F protocols.
  • Multi-factored Authentication - Built-in, advanced HOTP (One Time Password) technology that completes the unique multi-factored authentication process. Eliminate worry and help prevent losing your account info to theft, phishing, hacking, or other online scams. Note: Only Enterprise Users using Azure Active Directory can access Windows Hello log-in via Thetis FIDO2 Security Key.
  • Compact And Durable - 360° design with rotating aluminum alloy cover that shields the USB connector when not in use. Tough and durable alloy protects FIDO2 key from daily wear-and-tear, accidental drops, and scratches.
  • Portable Design - ultra-portable design allows you to take your FIDO key anywhere you need it.
// cypress/e2e/cognito-login.cy.js

describe('Cognito sign-in', () => {
  it('signs in through Cognito and reaches a protected page', () => {
    const cognitoUrl = Cypress.env('cognitoUrl');
    const appUrl = Cypress.env('appUrl');
    const email = Cypress.env('testEmail');
    const password = Cypress.env('testPassword');

    if (!cognitoUrl || !appUrl || !email || !password) {
      throw new Error('Set cognitoUrl, appUrl, testEmail, and testPassword in Cypress environment configuration.');
    }

    cy.visit(appUrl);

    // Replace this selector with the sign-in control in your application.
    cy.get('[data-cy="sign-in"]').click();

    cy.origin(
      cognitoUrl,
      { args: { email, password } },
      ({ email, password }) => {
        // These selectors are examples: use the actual controls rendered
        // by the configured Cognito sign-in experience.
        cy.get('input[name="username"]').type(email);
        cy.get('input[name="password"]').type(password, { log: false });
        cy.get('button[type="submit"]').click();
      }
    );

    // Replace with an app-specific URL or stable authenticated-state check.
    cy.location('origin').should('eq', appUrl);
    cy.get('[data-cy="account-home"]').should('be.visible');
  });
});

The example assumes a password form with the shown selectors and a sign-in action that returns to the application. Cognito pages and application wrappers can render different control names, and challenge-based flows need additional handling. Treat the selectors as the parts to align with your actual page rather than as universal Cognito selectors. Cypress also documents caching login state with cy.session(); use it when repeated interactive login is unnecessary for the test’s purpose.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Make the test prove the right outcome

A successful click on Submit is not proof that authentication succeeded. Assert a stable app-level result after the redirect, such as a protected page marker or an authenticated navigation element. If the test covers access control, go further: call or visit a protected resource and assert the expected authorization result. This catches cases where a login screen appears to complete but the application cannot use the resulting identity.

For OAuth authorization-code flows, retain browser-driven coverage if the redirect and code exchange are in scope. Cognito supports PKCE for authorization-code grants: the authorization request carries a code challenge and the token request supplies the original verifier. A programmatic call to an auth library does not automatically exercise that browser redirect and exchange.

Use programmatic authentication for tests after sign-in

When a test is about authenticated application behavior rather than the sign-in interface, establishing an authenticated state through the application’s auth library can avoid repeating the full browser login journey. Cypress’s example uses Amplify authentication and then places the resulting authentication data into the sample application’s localStorage, allowing that application to recognize the user.

That storage step is application-specific. Do not copy the sample’s local-storage mechanism into another app unless it is how that app’s auth implementation is designed to restore the signed-in user. Some applications delegate token handling to a library, use different storage, or refresh state through their own initialization path. Use the auth library and initialization method that your application itself uses.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep programmatic setup honest about its coverage

  • Use the project’s real auth library and the Cognito configuration used by the test environment.
  • Initialize the app in the same way it expects to restore a signed-in user; do not merely set a visual flag that makes the page look authenticated.
  • Assert a protected route or API outcome so the test checks behavior beyond a changed navigation bar.
  • Keep a separate browser-driven test for redirects, hosted UI behavior, and PKCE when those are requirements.

The exact programmatic call and state shape depend on the application’s auth-library version and setup. The documented Cypress example is tied to its Amplify-configured sample app; a generic snippet that writes arbitrary token keys to localStorage would risk testing a state your app never uses.

Rank #3
SecuX PUFido USB-C Security Key with PUF Technology, FIDO2/U2F Certified, Hardware-Rooted Unclonable Security for Passwordless Login and 2FA Authentication
  • A FIDO security key with PUF technology provides a unique, hardware-rooted trust anchor that resists tampering and cyber attacks, offering stronger security than conventional designs.
  • FIDO2 Certified Protection – Enjoy phishing-resistant security with FIDO2 certification, ensuring top-tier account safety across Windows, macOS, Linux, iOS iOS, Android and more.
  • Easy to use & Portable – Designed with a compact USB-C interface, Clife key fits easily on your keychain for secure access anywhere. Simply plug in and authenticate with ease.
  • Universal Compatibility – Works seamlessly with hundreds of FIDO2/U2F compliant services, including popular cloud, email, and social platforms.
  • Backup recommended – To ensure continuous access, register a backup Clife security key as a spare in case your primary key is lost.

Assert token-backed authorization, not just the page

Cognito user-pool sign-in returns JWTs. An application may use these tokens when calling a backend or resource server, which can validate the token and apply authorization rules. Match Cypress assertions to that design: check the user-facing result, then exercise a route or API request whose access depends on the authenticated identity.

Where your system uses access-token scopes, include an assertion that distinguishes allowed from disallowed access when that is part of the feature. A visible signed-in page alone does not prove a custom backend validated the token correctly. Custom webserver backends need token validation; AWS-managed services can validate Cognito JWTs through their configured integrations. The appropriate assertion depends on which architecture your application uses.

Reuse login state without hiding defects

cy.session() can cache authentication state so a suite does not repeat the interactive login for every test. This reduces duplicated setup, but session reuse should be a deliberate test-design choice, not a substitute for testing login itself.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Keep at least one browser-driven test for the login interaction when redirects or hosted login are important.
  2. Use a session for tests that need a signed-in user but do not test the sign-in journey.
  3. Control test users and backend data so a cached session does not conceal state-dependent behavior.
  4. Seed or reset data at the correct point in the test lifecycle. The Cypress sample seeds its database before authentication.

If a test depends on a newly created record, changed role, expired credential, or one-time challenge, confirm that the reused session and test data still represent the state the test intends to cover.

Handle Cognito flow differences explicitly

There is no single credential-and-submit sequence that covers every Cognito app. Managed login and SDK authentication have different supported behaviors. AWS documents third-party identity-provider sign-in through managed login or the classic hosted UI and redirect processing, while some custom authentication flows are SDK-only. Select the test path according to the configured project flow instead of assuming that a password form is a complete Cognito test.

  • MFA or one-time code: model the configured challenge and test account; do not expect the password submission alone to reach the app.
  • Passkey: treat it as a distinct authentication interaction rather than reusing a password-only test.
  • External identity provider: cover the configured redirect and callback behavior when it is part of the application’s login contract.
  • Custom auth: check whether the flow is supported through the browser experience or requires the SDK path used by the application.

Troubleshooting common failures

Cypress reports a cross-origin command problem

Make sure interactions with the Cognito origin run inside cy.origin(), and pass values needed by its callback through the supported argument mechanism rather than relying on outer-scope variables. Confirm the origin passed to cy.origin() matches the origin of the actual page, including scheme and host.

Rank #4
GoTrust Idem Key C USB Security Key NFC FIDO2 L2 Certified
  • Protect accounts with USB-C & NFC 2FA security key. Hardware-based authentication blocks phishing, credential theft & unauthorized access across cloud, enterprise & personal platforms.
  • FIDO2 Level 2 certified Security Key. Works with Apple ID, Microsoft Azure/Entra ID, AWS, Google, Facebook, Salesforce, DUO & more. Compatible with Chrome, Safari & Edge on all major OS.
  • Plug & play USB-C Security Key with NFC tap login. No software, drivers or batteries required. Works with Windows PC, MacBook, iPhone, Android & Chromebook for fast, secure authentication.
  • Built with FIPS 140-2 Level 3 secure element for advanced encryption. Trusted by IT teams, healthcare, education & government for secure authentication & identity protection.
  • IP68 waterproof, dustproof & crush-resistant design. Supports FIDO2, U2F, OTP, PIV, Mini Driver & smart card login. Durable USB security key for long-term enterprise & daily use.

The login form selectors time out

The configured sign-in page may not use the example selectors, or the test may have landed on a challenge or verification screen instead of the expected password form. Inspect the page for the test environment and update selectors and branching to match the configured flow. Avoid treating one set of field names as a Cognito-wide contract.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The test submits credentials but never returns to the app

Check that the test account can complete the enabled flow and that the application’s redirect configuration matches the environment. A pending MFA, verification, password-management step, or identity-provider interaction can make the assumed direct return invalid. Assert the expected redirect and handle the actual challenge rather than weakening the test to pass on submit.

The app appears signed in but protected requests fail

The UI may have restored partial state, or the backend may reject the token or its authorization context. Verify that your programmatic setup follows the app’s real token-storage and initialization design, then assert the protected API or route that represents the required authorization. Check token validation and scopes where your backend relies on them.

A cached session makes results inconsistent

Review whether test-user state, backend records, or roles changed between tests while the cached login remained reusable. Seed or reset state predictably and avoid session reuse for tests whose purpose involves the login interaction or a newly changed identity condition.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability, and test cost

Browser-driven authentication performs the redirect and page interaction that a programmatic setup omits, so it is the more direct way to cover those behaviors but also depends on the live login experience and its configuration. Programmatic setup can focus a test on authenticated features, but only if it creates the same kind of usable app state as the application’s auth implementation. Neither method removes the need to control test users, data, and configured challenges.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a small number of tests for the complete authentication journey and broader focused tests for protected features where that division fits your coverage goals. Keep assertions stable and user-visible where possible, and add authorization checks at the protected boundary rather than attempting to infer backend security from a page alone.

Best Value
ATLKey USB-C Security Key for Passkey & 2FA, FIDO2/U2F Certified with 3-Side Touch & Multi-Color LED, Stores 100 Passkeys, Phishing-Resistant Login for Google, Microsoft, Apple & More, IP68 Waterproof
  • PHISHING-RESISTANT 2FA: Cryptographically binds to real domains, making phishing attacks impossible unlike SMS codes or authenticator apps.
  • 3-SIDE CAPACITIVE TOUCH: Tap the end, left, or right side to authenticate, so it works in any orientation or crowded USB port.
  • MULTI-COLOR LED INDICATOR: Blue means ready, blinking blue means tap now, green means success, and red means error for instant status feedback.
  • IP68 WATERPROOF & BATTERY-FREE: Crush-resistant one-piece construction survives daily carry on a keychain or in a bag for years without any batteries.
  • UNIVERSAL COMPATIBILITY: Works with Google, Microsoft, Apple, GitHub, AWS, and any FIDO2 / U2F / WebAuthn service, storing up to 100 passkeys.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server, not a replacement for Cypress authentication assertions. It can capture a page for visual inspection, but it does not prove Cognito login, token issuance, redirect correctness, or protected-resource authorization. If you need screenshots of a page during a separate visual-check workflow, its one-call API can return an image or PDF:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. ScreenshotNeo accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; those steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and responses identify page verdict and billing status in headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000.

Sign up for 1,000 free screenshots a month, with no card required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Should every Cypress test log in through the Cognito page?

No. Reserve browser-driven login for coverage of the login and redirect behavior; use the app’s authentication setup for tests whose subject is behavior after sign-in.

Does programmatic authentication test Cognito PKCE?

Not by itself. PKCE behavior in the browser authorization-code flow needs coverage of the authorization request and code exchange.

Can ScreenshotNeo verify that Cognito authentication works?

No. It captures webpages; use Cypress and assertions against the authenticated app and protected resource to test authentication and authorization.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.