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

The right Cypress strategy depends on what you are testing. Use cy.origin() when the Cognito redirect and hosted sign-in experience are part of the behavior under test. Use programmatic authentication when you need a fast, authenticated starting state for tests whose subject is the application after login. Most mature suites use both, with cy.session() to reuse setup safely.

Choose the authentication path your test must cover

Decision Browser-driven cy.origin() Programmatic authentication
What it covers Cognito redirects and the user-facing sign-in interaction Application behavior after authentication, initialized through the application’s auth library
Main dependency Cognito domain, browser interaction, test credentials and redirect configuration Application auth-library configuration and a way to establish the state your app expects
Session strategy Cache the completed login with cy.session() Authenticate once, then initialize the app’s real auth state; adapt storage to your implementation
Limitation Tightly coupled to the hosted page and configured flow Does not by itself test hosted UI, redirects or the authorization-code/PKCE exchange

Do not treat the two approaches as competing standards. A browser test should cover the login flow when that flow matters; programmatic setup is appropriate for authorization, navigation and data tests that would otherwise repeat an unrelated sign-in screen.

Prepare an isolated Cognito test environment

Create test-only users and data

Use a user pool and app client intended for non-production testing, or otherwise ensure test accounts and backend records are isolated. Keep usernames, passwords, client identifiers and secrets in Cypress environment variables or your CI secret store, never in source control. Seed deterministic application data before establishing a session so cached authentication cannot hide data-dependent defects.

Check the app client before writing tests

The app-client configuration determines which sign-in methods are available. Password sign-in is only one possibility: the configured flow may require an email or SMS one-time password, MFA, a passkey or an external identity provider. Record the callback URL, allowed origins, scopes and enabled flows used by the test environment. A password-only fixture cannot prove that an MFA or passkey branch works.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
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.

Configure Cypress and the application

Make the application point at the test pool and test client when Cypress starts. Keep the Cognito domain and redirect URL consistent with the values registered in the app client. The exact provisioning commands and filenames depend on your project; examples that provision resources for a sample application should not be copied unchanged into another repository.

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

Use this pattern when redirect behavior, the hosted page, validation messages or the sign-in interaction are requirements. Cypress treats the Cognito domain as a different origin, so the interaction belongs inside cy.origin().

Minimal browser-driven example

describe('Cognito hosted login', () => {
  it('redirects back and opens a protected page', () => {
    cy.visit('/login')
    cy.get('[data-cy=sign-in]').click()

    cy.origin(Cypress.env('COGNITO_ORIGIN'),
      { args: {
          username: Cypress.env('E2E_USERNAME'),
          password: Cypress.env('E2E_PASSWORD')
        }
      }, ({ username, password }) => {
        cy.get('input[name="username"]').type(username)
        cy.get('input[name="password"]').type(password, { log: false })
        cy.get('button[type="submit"]').click()
      })

    cy.url().should('include', '/dashboard')
    cy.get('[data-cy=account-menu]').should('be.visible')
  })
})

Use selectors that are stable in your managed-login page and application. If your configured flow displays an MFA, one-time-code, passkey or identity-provider step, add an explicit branch for that step rather than assuming the password form is the final page. Never disable the flow merely to make this test pass.

Cache the interactive login with cy.session()

function loginThroughCognito() {
  cy.origin(Cypress.env('COGNITO_ORIGIN'),
    { args: {
        username: Cypress.env('E2E_USERNAME'),
        password: Cypress.env('E2E_PASSWORD')
      }
    }, ({ username, password }) => {
      cy.get('input[name="username"]').type(username)
      cy.get('input[name="password"]').type(password, { log: false })
      cy.get('button[type="submit"]').click()
    })
}

describe('authenticated area', () => {
  beforeEach(() => {
    cy.session('cognito-user', loginThroughCognito, {
      validate() {
        cy.visit('/dashboard')
        cy.get('[data-cy=account-menu]').should('be.visible')
      }
    })
  })

  it('loads protected data', () => {
    cy.visit('/dashboard')
    cy.get('[data-cy=protected-data]').should('be.visible')
  })
})

The validation callback should check something that requires a valid session, not merely that a local-storage key exists. Reset or reseed backend data where tests depend on a particular account state. Keep at least one separate test that always exercises the real login interaction.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

Authenticate programmatically for post-login tests

Programmatic setup is faster when the test concerns a protected route, component or API and not the hosted sign-in interface. The Cypress guide demonstrates authenticating through the application’s Amplify integration and then placing the resulting state in the sample app’s localStorage. That storage format is application-specific: inspect your own auth adapter and reproduce only the state your application actually reads.

Example using the application auth library

function signInProgrammatically() {
  cy.then(() => {
    // Import and call the same auth integration used by the app.
    return cy.task('cognitoSignIn', {
      username: Cypress.env('E2E_USERNAME'),
      password: Cypress.env('E2E_PASSWORD')
    })
  }).then((authState) => {
    // Replace this with your app's documented state/bootstrap mechanism.
    cy.window().then((win) => {
      win.localStorage.setItem('app-auth-state', JSON.stringify(authState))
    })
  })
}

beforeEach(() => {
  cy.session('programmatic-user', signInProgrammatically, {
    validate() {
      cy.request({
        url: '/api/me',
        failOnStatusCode: false
      }).its('status').should('eq', 200)
    }
  })
})

cy.task('cognitoSignIn') above is a project task, not a built-in Cypress command. Implement it with the same Amplify or Cognito SDK configuration used by your application, keep credentials on the Node side, and return only what the browser bootstrap requires. If your app stores tokens in cookies, use its supported cookie setup instead of writing local storage. If it refreshes tokens in memory, initialize that provider through a test-only bootstrap API.

Know what this shortcut does not prove

A programmatic sign-in does not exercise the hosted page, redirect URI handling, browser cookie behavior or an authorization-code exchange. In particular, it does not prove PKCE. Keep a browser-driven test for any redirect and code-exchange behavior that is in scope.

Cover OAuth, PKCE and managed-login branches

For an authorization-code flow with PKCE, the browser sends a code challenge in the authorization request and later sends the original verifier when exchanging the code for tokens. Assert the complete redirect path with cy.origin() and your registered callback URL; a successful API call after programmatic login is not evidence that PKCE works.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

Cognito managed login provides user-facing pages for operations such as password management, MFA and attribute verification. Test the branches your app has enabled, including cancellation, invalid credentials, expired or reused one-time codes and a user who must change a password. Third-party identity-provider sign-in also depends on the managed-login or hosted-UI redirect arrangement; keep those tests separate from SDK-only custom authentication flows.

Assert both the UI and authorization boundary

Verify the visible result

After redirect, assert a stable application element such as an account menu, user name or protected route. Avoid asserting only the URL: a redirect can succeed while the app fails to hydrate its auth provider.

Exercise a protected request

cy.request({
  url: '/api/private-report',
  failOnStatusCode: false
}).then((response) => {
  expect(response.status).to.eq(200)
  expect(response.body).to.have.property('report')
})

Use a request whose authorization is meaningful for the user and scope under test. A resource server should validate the user-pool token’s issuer, signature, validity and, where configured, access-token scopes. AWS-managed integrations can perform validation through their configured integration; a custom backend must implement validation itself. Test a denied case as well, such as a user lacking the required scope or role, and assert the expected 401 or 403 behavior.

Do not inspect tokens unnecessarily

Assertions should follow your real token-storage and backend-validation design. Avoid logging JWTs or placing long-lived credentials in screenshots, Cypress videos or CI artifacts. If a test must inspect claims, redact the token and assert only the claim required for that case.

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.
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.

Troubleshoot common failures

“cy.origin” fails or the page is blank

  • Confirm that the origin passed to cy.origin() exactly matches the Cognito domain, including scheme and host.
  • Check that the callback URL registered on the app client is the URL Cypress actually uses.
  • Wait for a specific form selector instead of relying on an arbitrary delay, and verify the test account can sign in outside Cypress.

The password test stops at MFA or a code prompt

The configured flow requires another challenge. Add a controlled test-user strategy for that challenge, or create a separate test that explicitly covers it. Do not silently bypass MFA in the only login test.

The UI says “logged in” but the API returns 401

  • Confirm that the app sent the access token or cookie expected by the API, not merely an ID token or stale storage value.
  • Check issuer, audience, expiry and required scopes in backend validation.
  • Clear cached sessions after changing pool, client or scope settings.

Session reuse leaks state between tests

Use unique session identifiers for materially different users, seed data before authentication, and make validation perform a real protected request. Clear or recreate records whose status changes during a test.

CI cannot authenticate while local runs pass

Compare CI callback URLs, environment variables, clock settings and network egress with local configuration. Ensure the CI user is confirmed and that secrets are available to the Cypress process that performs the sign-in.

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

Reliability, speed and security practices

  • Keep one or a small number of end-to-end tests for the complete hosted flow; use programmatic setup for the larger post-login suite.
  • Use deterministic test users and data, and avoid sharing one mutable account across parallel jobs unless the data model supports it.
  • Prefer selector-based waits and assertions over fixed sleeps.
  • Expire or rotate test credentials and prevent Cypress command logs, videos and screenshots from exposing passwords or tokens.
  • When changing app-client flows, callback URLs, scopes or token storage, update both authentication strategies and their negative tests.

Or skip the browser setup

If your goal is capturing a page for test documentation or a visual artifact—not authenticating the application—ScreenshotNeo can return a screenshot with one request. It accepts consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups and chat widgets before capture. Bot checks, blank pages, timeouts, failed loads and cache hits are not billed, and the response identifies the page verdict and billing status in headers. Its MCP server lets Claude, Cursor and other MCP clients call take_screenshot, get_page_info and capture_pdf.

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.
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 options such as viewport and device presets, full-page lazy-image loading, CSS selectors, dark mode, custom JavaScript, network-idle waits, request blocking, cookies, headers, geolocation, PDF output, caching and async webhooks. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account to get started.

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.

Frequently Asked Questions

Should every Cypress test log in through Cognito?

No. Reserve browser-driven login for the interaction and redirect coverage that matters; reuse a validated session or programmatic setup for tests focused on authenticated application behavior.

Can a programmatic token test replace a PKCE test?

No. PKCE requires testing the authorization request, redirect and code exchange with the verifier. Programmatic authentication bypasses that browser path.

How should MFA be tested?

Model MFA as an explicit configured branch with controlled test users and challenge handling. A password-only fixture does not cover an MFA-enabled client.

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

Where should Cognito credentials live?

In Cypress environment variables or your CI secret manager, never committed source, fixtures, command logs or screenshots.

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.