### Install Dependencies Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/end-to-end-example/client/README.md Installs all necessary project dependencies. Ensure NodeJS is installed and the back-end is deployed before running. ```bash npm install ``` -------------------------------- ### Install Passwordless Auth Library Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/react/README-REACT-NATIVE.md Install the main library package for passwordless authentication. ```shell npm install amazon-cognito-passwordless-auth ``` -------------------------------- ### Run Development Server Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/end-to-end-example/client/README.md Starts the local development server for the React application. The app will be accessible at http://localhost:5173/. ```bash npm run dev ``` -------------------------------- ### Example iOS Associated Domains Configuration Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/react/README-REACT-NATIVE.md A concrete example of the `apple-app-site-association` JSON file with placeholder values replaced by a sample team identifier and app bundle ID. ```json { "applinks": {}, "webcredentials": { "apps": ["H123456789.com.example.app"] }, "appclips": {} } ``` -------------------------------- ### Configure Custom Token Storage Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/README.md Customize token storage by providing a custom storage class to the Passwordless configuration. This example demonstrates using in-memory storage to avoid using localStorage. ```javascript import { Passwordless } from "amazon-cognito-passwordless-auth"; class MemoryStorage { constructor() { this.memory = new Map(); } getItem(key) { return this.memory.get(key); } setItem(key, value) { this.memory.set(key, value); } removeItem(key) { this.memory.delete(key); } } Passwordless.configure({ ..., // other config storage: new MemoryStorage(), }); ``` -------------------------------- ### Sign in with Magic Link in Node.js (Mocked) Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/README-NON-WEB.md Sign in a user using a magic link in a Node.js environment. This example mocks the `location` and `history` global objects to simulate a browser environment for link processing. ```typescript import { Passwordless } from "amazon-cognito-passwordless-auth"; import { signInWithLink } from "amazon-cognito-passwordless-auth/magic-link"; Passwordless.configure({ clientId: "", cognitoIdpEndpoint: "", // override location, let's pretend the current href is the magic link: location: { href: "https://abcdefghijk.cloudfront.net/#eyactualmagiclinkyrqfhahsv89grhz9rghrzhbvzxcvcbhzdrt4ut9qg...", hostname: "abcdefghijk.cloudfront.net", }, // override history, mock implementation: history: { pushState: () => {}, }, }); const { signedIn } = signInWithLink(); const tokens = await signedIn; console.log(tokens); ``` -------------------------------- ### iOS Associated Domains Configuration Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/react/README-REACT-NATIVE.md Example JSON structure for serving the `apple-app-site-association` file to configure associated domains for passkey authentication on iOS. ```json { "applinks": {}, "webcredentials": { "apps": ["".""] }, "appclips": {} } ``` -------------------------------- ### Install React Native Passkey Dependency Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/react/README-REACT-NATIVE.md Install the `react-native-passkey` peer dependency, which is required for using passkeys in React Native. ```shell npm install react-native-passkey@^2.1.1 ``` -------------------------------- ### FIDO2 Credential Registration Sequence Diagram Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/FIDO2.md This sequence diagram illustrates the process of registering a new FIDO2 authenticator. It outlines the interactions between the browser, WebAuthn API, REST API, Lambda, and DynamoDB, starting from user sign-in and ending with successful authenticator activation. ```mermaid sequenceDiagram autonumber actor User participant BJS as Browser JavaScript participant BLS as Browser Storage participant BC as Browser WebAuthn core participant API as REST API+Lambda participant DB as DynamoDB BJS->>BLS: Query user FIDO2 enabled Activate BJS Activate BLS BLS->>BJS: null Deactivate BLS BJS->>User: Show enable-face-or-touch-login dialog Deactivate BJS Activate User User->>BJS: Click "Enable Face or Touch sign-in" Activate BJS BJS->>API: Start create-credential, include JWT (ID token) Activate API API->>API: Verify JWT API->>API: Generate random challenge API->>DB: Store challenge Activate DB DB->>API: OK Deactivate DB API->>BJS: Challenge and other FIDO2 options Deactivate API BJS->>BC: navigator.credentials.create() Activate BC BC->>User: Show register-authenticator native dialog User->>BC: Execute gesture (e.g. touch, face) BC->>BJS: FIDO2 public key response Deactivate BC BJS->>User: Show input-friendly-authenticator-name custom dialog User->>BJS: Friendly name BJS->>API: Complete create-credential Activate API API->>DB: Lookup challenge Activate DB DB->>API: Challenge Deactivate DB API->>API: Verify authenticator response API->>DB: Store credential Activate DB DB->>API: OK Deactivate DB API->>BJS: Credential metadata Deactivate API BJS->>BLS: Store FIDO2 enabled user Activate BLS BLS->>BJS: OK Deactivate BLS BJS->>User: "Authenticator activated successfully" Deactivate BJS Deactivate User ``` -------------------------------- ### Customize Passwordless Component Size Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/react/README-REACT.md Override the default size of the main container for the Passwordless component by adjusting the CSS. This example sets the height to fill the viewport. ```css .passwordless-main-container { height: 100vh !important; } ``` -------------------------------- ### Sign Up Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/README.md Register a new user with username, password, and optional user attributes. ```APIDOC ## Sign Up If your User Pool is enabled for self sign-up, users can sign up like so: ```javascript import { signUp } from "amazon-cognito-passwordless-auth/cognito-api"; export default function YourComponent() { // Sample form that allows the user to sign up return (
{ signUp({ username: event.currentTarget.username.value, password: event.currentTarget.password.value, // userAttributes are optional and you can pass any Cognito User pool attributes // Read more: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html userAttributes: [ { name: "name", value: event.currentTarget.name.value, }, ], }); event.preventDefault(); }} >
); } ``` ``` -------------------------------- ### Sample React Components Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/react/README-REACT.md The library provides sample components to facilitate quick integration and serve as inspiration for custom UI development. ```APIDOC ## Sample React Components ### `` #### Description A sample component that renders a login page, allowing users to choose between FIDO2 and Magic Link authentication methods. ### `` #### Description A sample 'toast' component displayed at the top of the page. It serves two purposes: 1. Recommends adding a FIDO2 credential if the user does not have one. 2. Displays the user's registered FIDO2 credentials. ``` -------------------------------- ### Configure Passwordless Client Source: https://context7.com/aws-samples/amazon-cognito-passwordless-auth/llms.txt Initializes the client library. Must be called once before any auth function. Provide cognitoIdpEndpoint or userPoolId. Optionally pass fido2.baseUrl and a custom storage object. ```typescript import { Passwordless } from "amazon-cognito-passwordless-auth"; // ── Option A: minimal web setup ────────────────────────────────────────────── Passwordless.configure({ cognitoIdpEndpoint: "eu-west-1", clientId: "6rp0jxxxxxxxxxxxxxxxx", userPoolId: "eu-west-1_ABcDefGhI", fido2: { baseUrl: "https://abc123.execute-api.eu-west-1.amazonaws.com/v1/", authenticatorSelection: { userVerification: "required", residentKey: "preferred", }, timeout: 60_000, }, debug: console.debug, }); ``` ```typescript import { Amplify } from "aws-amplify"; Amplify.configure({ /* ... */ }); Passwordless.configureFromAmplify(Amplify.configure()).with({ fido2: { baseUrl: "https://abc123.execute-api.eu-west-1.amazonaws.com/v1/" }, }); ``` ```typescript class MemoryStorage { private memory = new Map(); getItem(key: string) { return this.memory.get(key); } setItem(key: string, value: string) { this.memory.set(key, value); } removeItem(key: string) { this.memory.delete(key); } } Passwordless.configure({ cognitoIdpEndpoint: "us-east-1", clientId: "6rp0jxxxxxxxxxxxxxxxx", storage: new MemoryStorage(), // Non-browser environments: override globals fetch: customFetch, crypto: customCrypto, location: { href: "https://app.example.com/", hostname: "app.example.com" }, history: { pushState: (_d, _u, url) => console.log("nav to", url) }, }); ``` -------------------------------- ### Passwordless.configure Source: https://context7.com/aws-samples/amazon-cognito-passwordless-auth/llms.txt Initializes the client library. This must be called once before any authentication function. You can provide either a `cognitoIdpEndpoint` or a `userPoolId` to infer the AWS region. Optionally, configure `fido2.baseUrl` and a custom `storage` object. ```APIDOC ## Client: `Passwordless.configure` Initialises the client library. Must be called once before any auth function. Either provide a `cognitoIdpEndpoint` (AWS region string or full proxy URL) or a `userPoolId` from which the region is inferred automatically. Optionally pass `fido2.baseUrl` (the URL output from the CDK stack) and a custom `storage` object. ```typescript import { Passwordless } from "amazon-cognito-passwordless-auth"; // ── Option A: minimal web setup ────────────────────────────────────────────── Passwordless.configure({ cognitoIdpEndpoint: "eu-west-1", clientId: "6rp0jxxxxxxxxxxxxxxxx", userPoolId: "eu-west-1_ABcDefGhI", fido2: { baseUrl: "https://abc123.execute-api.eu-west-1.amazonaws.com/v1/", authenticatorSelection: { userVerification: "required", residentKey: "preferred", }, timeout: 60_000, }, debug: console.debug, }); // ── Option B: configure from existing Amplify config ───────────────────────── import { Amplify } from "aws-amplify"; Amplify.configure({ /* ... */ }); Passwordless.configureFromAmplify(Amplify.configure()).with({ fido2: { baseUrl: "https://abc123.execute-api.eu-west-1.amazonaws.com/v1/" }, }); // ── Option C: memory-only token storage (e.g. for security-sensitive apps) ─── class MemoryStorage { private memory = new Map(); getItem(key: string) { return this.memory.get(key); } setItem(key: string, value: string) { this.memory.set(key, value); } removeItem(key: string) { this.memory.delete(key); } } Passwordless.configure({ cognitoIdpEndpoint: "us-east-1", clientId: "6rp0jxxxxxxxxxxxxxxxx", storage: new MemoryStorage(), // Non-browser environments: override globals fetch: customFetch, crypto: customCrypto, location: { href: "https://app.example.com/", hostname: "app.example.com" }, history: { pushState: (_d, _u, url) => console.log("nav to", url) }, }); ``` ``` -------------------------------- ### Override Email Sender for Magic Links Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/CUSTOMIZE-AUTH.md Replace the default email sending mechanism with a custom provider. This example demonstrates how to integrate with an external email SDK to send magic link emails. ```typescript import { magicLink } from "amazon-cognito-passwordless-auth/custom-auth"; export { createAuthChallengeHandler as handler } from "amazon-cognito-passwordless-auth/custom-auth"; import sendEmail from "your-email-provider-sdk"; magicLink.configure({ async emailSender({ emailAddress, content }) { return sendEmail({ email: emailAddress, subject: content.subject.data, message: content.html.data, }); }, }); ``` -------------------------------- ### Deploy Single Page Application Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/end-to-end-example/client/README.md Deploys the React application to S3, served by CloudFront. The CloudFront URL will be available in the back-end's CDK stack outputs. ```bash ./deploy-spa.cjs ``` -------------------------------- ### Request Magic Link for Sign-In Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/react/README-REACT.md Use this hook to request a magic link to be emailed to the user. The link, when clicked, will automatically sign the user in if the library is initialized in the web app. An optional redirect URI can be provided. ```javascript import { usePasswordless } from "amazon-cognito-passwordless-auth"; export default function YourComponent() { const { requestSignInLink } = usePasswordless();
{ // Request a magic link to be e-mailed to the user. // When the user clicks on the link, your web app will open and parse the link // automatically (if you've loaded this library), and sign the user in. // Supply an optional redirectUri as the second argument to specify where // in your application you'd like the user to be directed to after signing in. requestSignInLink({ username: event.currentTarget.username.value, redirectUri: "https://example.com/article/45", }); event.preventDefault(); }} >
; } ``` -------------------------------- ### Customize Magic Link Email Template Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/CUSTOMIZE-AUTH.md Override the default email content creator to use a custom HTML and text template for magic link emails. This example shows how to access the secret login link and expiry time to build a personalized email. ```typescript import { magicLink } from "amazon-cognito-passwordless-auth/custom-auth"; // Export the solution's handler to be the handler of YOUR Lambda function too: export { createAuthChallengeHandler as handler } from "amazon-cognito-passwordless-auth/custom-auth"; // Calling configure() without arguments retrieves the current configuration: const defaultConfig = magicLink.configure(); // Add your own logic: magicLink.configure({ async contentCreator({ secretLoginLink }) { return { html: { data: `

Your secret sign-in link: sign in

This link is valid for ${Math.floor( defaultConfig.secondsUntilExpiry / 60 )} minutes

`, charSet: "UTF-8", }, text: { data: `Your secret sign-in link: ${secretLoginLink}`, charSet: "UTF-8", }, subject: { data: "Your secret sign-in link", charSet: "UTF-8", }, }; }, }); ``` -------------------------------- ### React: Passwordless and Fido2Toast Components Source: https://context7.com/aws-samples/amazon-cognito-passwordless-auth/llms.txt Use the prebuilt `` component for sign-in UI and `` for FIDO2 recommendations and credential management. Ensure `PasswordlessContextProvider` wraps your application. ```tsx import { Passwordless, Fido2Toast, PasswordlessContextProvider, } from "amazon-cognito-passwordless-auth/react"; import "amazon-cognito-passwordless-auth/passwordless.css"; export default function App() { return ( {/* Wraps children: renders sign-in UI when NOT_SIGNED_IN, renders children when SIGNED_IN * / {/* App content shown when signed in * / {/* FIDO2 recommendation + credential manager overlay * / ); } ``` -------------------------------- ### Configure Passwordless Auth Library Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/README.md Configure the library with your Cognito details and optional FIDO2 settings. Ensure all required parameters like `cognitoIdpEndpoint`, `clientId`, and `userPoolId` are provided. ```javascript import { Passwordless } from "amazon-cognito-passwordless-auth/react"; Passwordless.configure({ cognitoIdpEndpoint: "eu-west-1", // you can also use the full endpoint URL, potentially to use a proxy clientId: "", // optional, only required if you want to use FIDO2: fido2: { baseUrl: "", /** * all other FIDO2 config is optional, values below are examples only to illustrate what you might configure. * (this client side config is essentially an override, that's merged on top of the config received from the backend) */ authenticatorSelection: { userVerification: "required", requireResidentKey: true, residentKey: "preferred", authenticatorAttachment: "platform", }, rp: { id: "example.com", name: "Example", }, attestation: "direct", extensions: { appid: "u2f.example.com", credProps: true, hmacCreateSecret: true, }, timeout: 120000, }, userPoolId: "", // optional, only required if you want to use USER_SRP_AUTH // optional, additional headers that will be sent with each request to Cognito: proxyApiHeaders: { "
": "", "
": "", }, storage: localStorage, // Optional, default to localStorage }); ``` -------------------------------- ### Configuration Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/README.md Configure the Passwordless library with your AWS Cognito details and optional FIDO2 settings. ```APIDOC ## Configuration To use the library, you need to first configure it: ```javascript import { Passwordless } from "amazon-cognito-passwordless-auth/react"; Passwordless.configure({ cognitoIdpEndpoint: "eu-west-1", // you can also use the full endpoint URL, potentially to use a proxy clientId: "", // optional, only required if you want to use FIDO2: fido2: { baseUrl: "", /** * all other FIDO2 config is optional, values below are examples only to illustrate what you might configure. * (this client side config is essentially an override, that's merged on top of the config received from the backend) */ authenticatorSelection: { userVerification: "required", requireResidentKey: true, residentKey: "preferred", authenticatorAttachment: "platform", }, rp: { id: "example.com", name: "Example", }, attestation: "direct", extensions: { appid: "u2f.example.com", credProps: true, hmacCreateSecret: true, }, timeout: 120000, }, userPoolId: "", // optional, only required if you want to use USER_SRP_AUTH // optional, additional headers that will be sent with each request to Cognito: proxyApiHeaders: { "
": "", "
": "", }, storage: localStorage, // Optional, default to localStorage }); ``` ``` -------------------------------- ### Initiate FIDO2 Sign-in Source: https://context7.com/aws-samples/amazon-cognito-passwordless-auth/llms.txt Initiates a FIDO2 sign-in flow via Cognito CUSTOM_AUTH. If username is omitted, requests a usernameless passkey challenge. Returns { signedIn: Promise, abort: () => void }. ```typescript import { authenticateWithFido2 } from "amazon-cognito-passwordless-auth/fido2"; // ── Usernameless passkey sign-in ────────────────────────────────────────────── const { signedIn, abort } = authenticateWithFido2({ statusCb: (status) => { // status: "STARTING_SIGN_IN_WITH_FIDO2" | "COMPLETING_SIGN_IN_WITH_FIDO2" // | "SIGNED_IN_WITH_FIDO2" | "FIDO2_SIGNIN_FAILED" console.log("Auth status:", status); }, }); try { const tokens = await signedIn; // tokens.accessToken, tokens.idToken, tokens.refreshToken, tokens.expireAt, tokens.username console.log("Signed in as:", tokens.username); } catch (err) { console.error("Sign-in failed:", err); } ``` ```typescript // ── Username + known credential IDs (non-discoverable) ─────────────────────── const { signedIn: signedIn2 } = authenticateWithFido2({ username: "alice@example.com", credentials: [ { id: "base64url-credential-id", transports: ["internal"] }, ], tokensCb: async (tokens) => { // Custom callback instead of the default storage handler console.log("Got tokens:", tokens); }, statusCb: (s) => console.log(s), clientMetadata: { appVersion: "2.1.0" }, }); await signedIn2; ``` ```typescript // ── Abort in-flight sign-in ──────────────────────────────────────────────────── const operation = authenticateWithFido2({ username: "alice@example.com" }); setTimeout(() => operation.abort(), 5000); // cancel after 5 s ``` -------------------------------- ### Configure Passwordless Auth for Non-Web Runtimes Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/README-NON-WEB.md Configure the library for non-web runtimes by providing custom implementations for global variables like storage, fetch, crypto, location, and history. A client secret is recommended for server-side usage. ```javascript import { Passwordless } from "amazon-cognito-passwordless-auth"; Passwordless.configure({ ...otherConfig, clientSecret: "secret", // User Pool Client secret storage: YourStorageImplementation, // Custom storage implementation––if not provided and localStorage is undefined then MemoryStorage is used fetch: YourFetchImplementation, // Custom fetch implementation crypto: YourCryptoImplementation, // Custom crypto implementation location: YourLocationImplementation, // Custom location implementation history: YourHistoryImplementation, // Custom history implementation }); ``` -------------------------------- ### Integrate FIDO2 Toast and Passwordless Component Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/react/README-REACT.md Combine the PasswordlessContextProvider, PasswordlessComponent, and Fido2Toast for a complete authentication experience, including FIDO2 prompts. Ensure CSS is imported. ```typescript import { PasswordlessContextProvider, Passwordless as PasswordlessComponent, Fido2Toast, } from "amazon-cognito-passwordless-auth/react"; import "amazon-cognito-passwordless-auth/passwordless.css"; ReactDOM.createRoot(document.getElementById("root")).render( ", customerName: "ACME corp.", customerLogoUrl: "", }}> ); ``` -------------------------------- ### FIDO2 Sign-in with Username Sequence Diagram Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/FIDO2.md This diagram illustrates the sequence of interactions between a user's browser, Amazon Cognito, and other services during a FIDO2 sign-in process when the username is already known. It covers the initiation of authentication, challenge generation, WebAuthn interaction, and final JWT token retrieval. ```mermaid sequenceDiagram autonumber actor User participant BJS as Browser JavaScript participant BLS as Browser Storage participant BC as Browser WebAuthn core participant C as Cognito participant DA as DefineAuth participant CA as CreateAuthChallenge participant VA as VerifyAnswer participant DB as DynamoDB User->>BJS: Open web app Activate User Activate BJS BJS->>BLS: Query FIDO2 enabled users Activate BLS BLS->>BJS: FIDO2 Users Deactivate BLS BJS->>User: Show username sign-in buttons Deactivate BJS User->>BJS: Click "Sign-in as with face or touch" Activate BJS BJS->>C: InitiateAuth Activate C C->>DA: Invoke Activate DA DA->>C: Custom challenge Deactivate DA C->>CA: Invoke Activate CA CA->>CA: Generate challenge CA->>DB: Query credential IDs Activate DB DB->>CA: Credential IDs Deactivate DB CA->>C: FIDO2 challenge, credential IDs, options Deactivate CA C->>BJS: FIDO2 challenge, credential IDs, options Deactivate C BJS->>BC: navigator.credentials.get() Activate BC BC->>User: Show sign-use-authenticator native dialog User->>BC: Execute gesture (e.g. touch, face) BC->>BJS: FIDO2 signature response Deactivate BC BJS->>C: RespondToAuthChallenge Activate C C->>VA: Invoke Activate VA VA->>VA: Verify client data VA->>VA: Verify challenge VA->>DB: Get credential public key Activate DB DB->>VA: Credential public key Deactivate DB VA->>VA: Verify signature VA->>C: Answer correct: true Deactivate VA C->>DA: Invoke Activate DA DA->>C: Succeed Auth Deactivate DA C->> BJS: JWTs Deactivate C BJS->>BLS: Store JWTs Activate BLS BLS->>BJS: OK Deactivate BLS BJS->>User: "You are signed in" Deactivate BJS Deactivate User ``` -------------------------------- ### User Sign Up with Cognito Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/README.md Implement a form for users to sign up. This function handles the creation of a new user in your Cognito User Pool, optionally accepting additional user attributes. ```javascript import { signUp } from "amazon-cognito-passwordless-auth/cognito-api"; export default function YourComponent() { // Sample form that allows the user to sign up return (
{ signUp({ username: event.currentTarget.username.value, password: event.currentTarget.password.value, // userAttributes are optional and you can pass any Cognito User pool attributes // Read more: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html userAttributes: [ { name: "name", value: event.currentTarget.name.value, }, ], }); event.preventDefault(); }} >
); } ``` -------------------------------- ### Sign in with Magic Link in Node.js (Custom Classes) Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/README-NON-WEB.md Sign in a user using a magic link in Node.js with custom class implementations for `Location` and `History`. This provides a more structured way to mock browser globals for link handling. ```typescript import { Passwordless } from "amazon-cognito-passwordless-auth"; import { MinimalLocation, MinimalHistory, } from "amazon-cognito-passwordless-auth/config"; import { signInWithLink } from "amazon-cognito-passwordless-auth/magic-link"; class CustomLocation implements MinimalLocation { /** * Implement a mechanism in Node.js to acquire and provide the magic link: */ get href() { return "https://abcdefghijk.cloudfront.net/#eyactualmagiclinkyrqfhahsv89grhz9rghrzhbvzxcvcbhzdrt4ut9qg..."; } /** * Implement a mechanism in Node.js to provide the hostname (used as default RP ID in FIDO2, unless configured itself): */ get hostname() { return "abcdefghijk.cloudfront.net"; } } class CustomHistory implements MinimalHistory { /** * Implement a mechanism in Node.js to change the current URL (probably not applicable in CLI scripts!) */ pushState() {} } Passwordless.configure({ clientId: "", cognitoIdpEndpoint: "", // override location location: new CustomLocation(), // override history history: new CustomHistory(), }); const { signedIn } = signInWithLink(); const tokens = await signedIn; console.log(tokens); ``` -------------------------------- ### Configure Custom Lambda Function Entry Point Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/CUSTOMIZE-AUTH.md Specify a custom entry point for the `createAuthChallenge` Lambda function within the Passwordless CDK construct. This allows your custom Lambda code to be used instead of the default. ```typescript const passwordless = new Passwordless(this, "Passwordless", { ...other, functionProps: { createAuthChallenge: { // Override entry, to point to your custom code: entry: join(__dirname, "create-auth-challenge/index.ts"), bundling: { // Solves `Dynamic require of "stream" is not supported"` error: banner: "import{createRequire}from 'module';const require=createRequire(import.meta.url);", }, }, }, }); ``` -------------------------------- ### Configure Passwordless Auth for React Native Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/react/README-REACT-NATIVE.md Set up the Passwordless library for React Native, ensuring AsyncStorage is used for storage and configuring optional FIDO2 and proxy settings. ```javascript import AsyncStorage from "@react-native-async-storage/async-storage"; import { PasswordlessContextProvider, Passwordless, } from "amazon-cognito-passwordless-auth"; // In React Native: import from top-level module function App() { Passwordless.configure({ cognitoIdpEndpoint: "eu-west-1", // you can also use the full endpoint URL, potentially to use a proxy clientId: "", // optional, only required if you want to use FIDO2: fido2: { baseUrl: "", /** * React Native Passkey Domain. Used by iOS and Android to link your app's passkeys to your domain * That domain must serve the mandatory manifest json required by Apple and Google under the following paths: * - iOS: https:///.well-known/apple-app-site-association * - Android: https:///.well-known/assetlinks.json * More info: * - iOS: https://developer.apple.com/documentation/xcode/supporting-associated-domains * - Android: https://androiddeveloper.android.com/training/sign-in/passkeys#add-support-dal */ passkeyDomain: "", /** * Configure Relying Party ID */ rp: { id: "example.com", // default: your passkeyDomain name: "Example.com", // default: your passkeyDomain }, }, userPoolId: "", // optional, only required if you want to use USER_SRP_AUTH // optional, additional headers that will be sent with each request to Cognito: proxyApiHeaders: { "
": "", "
": "", }, storage: AsyncStorage, // Need to set this for React Native, as the default (localStorage) will not work }); // Your original App here } export default function AppWrapped() { return ( ); } ``` -------------------------------- ### Wrap App with Passwordless Component Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/react/README-REACT.md Use this component to wrap your application. It renders your app once the user is successfully signed in. ```jsx ``` -------------------------------- ### Create FIDO2 Credential Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/react/README-REACT.md Initiate the creation of a FIDO2 (WebAuthn) credential for the user. This will trigger the native WebAuthn dialog for biometric or device authentication. The returned credential object includes methods for updating or deleting it. ```javascript import { usePasswordless } from "amazon-cognito-passwordless-auth/react"; export default function YourComponent() { const { fido2CreateCredential } = usePasswordless(); return (
{ fido2CreateCredential({ friendlyName: event.currentTarget.friendlyName.value, }).then((credential) => { // The credential object will look like this: // credential = { // credentialId: string; // friendlyName: string; // createdAt: Date; // lastSignIn?: Date; // signCount: number; // update: (friendlyName: string) => void; // function to update the friendlyName // delete: () => void; // function to delete the credential // busy: boolean; // set to true if the credential is being updated or deleted // } console.log(credential); }); event.preventDefault(); }} >
); } ``` -------------------------------- ### Configure Passwordless Auth from Amplify Configuration Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/README.md Use this method to configure the Passwordless library using your existing Amplify configuration. It allows seamless integration when both Amplify and this library are used together. ```typescript import { Passwordless } from "amazon-cognito-passwordless-auth"; import { Amplify } from "aws-amplify"; // Configure Amplify: Amplify.configure({ ... }) // Next, configure Passwordless from Amplify: Passwordless.configureFromAmplify(Amplify.configure()); ``` ```typescript Passwordless.configureFromAmplify(Amplify.configure()).with({ fido2: { baseUrl: "...", }, }); ``` -------------------------------- ### storeTokens / retrieveTokens Source: https://context7.com/aws-samples/amazon-cognito-passwordless-auth/llms.txt Provides low-level utilities for persisting and reading tokens from a configured storage mechanism. The storage keys adhere to the Amplify-compatible format, allowing interoperability between this library and Amplify. ```APIDOC ## Client: `storeTokens` / `retrieveTokens` Low-level helpers for persisting and reading tokens from configured storage. The storage keys are Amplify-compatible, so Amplify can read tokens stored by this library and vice-versa. ```typescript import { storeTokens, retrieveTokens, } from "amazon-cognito-passwordless-auth/storage"; // ── Store tokens after a custom tokensCb ───────────────────────────────────── await storeTokens({ accessToken: "eyJra...", idToken: "eyJra...", refreshToken: "eyJjb...", expireAt: new Date(Date.now() + 3600 * 1000), }); // ── Retrieve tokens (e.g. for an authenticated API call) ───────────────────── const tokens = await retrieveTokens(); if (!tokens?.accessToken) { redirectToLogin(); } else { const response = await fetch("https://api.example.com/data", { headers: { Authorization: `Bearer ${tokens.accessToken}` }, }); } ``` ``` -------------------------------- ### Sign In with Username and Password (SRP or Plaintext) Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/react/README-REACT.md Use this hook to authenticate users with their username and password. It supports both Secure Remote Password (SRP) protocol for enhanced security and plaintext password authentication. Ensure the correct authentication method is selected based on your security requirements. ```javascript import { usePasswordless } from "amazon-cognito-passwordless-auth"; export default function YourComponent() { const { authenticateWithSRP, authenticateWithPlaintextPassword } = usePasswordless(); // Sample form that allows the user to sign up return (
{ if (event.currentTarget.srp) { authenticateWithSRP({ username: event.currentTarget.username.value, password: event.currentTarget.password.value }); } else { authenticateWithPlaintextPassword({ username: event.currentTarget.username.value, password: event.currentTarget.password.value }); } event.preventDefault(); }} > Use Secure Remote Password (SRP)
); } ``` -------------------------------- ### Request Magic Link Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/react/README-REACT.md This function requests a magic link to be emailed to the user. The user can then click this link to sign in to the application. An optional redirect URI can be provided to specify where the user should be directed after signing in. ```APIDOC ## Request Magic Link ### Description Requests a magic link to be emailed to the user for passwordless authentication. The user clicks the link to complete the sign-in process. ### Method Signature `requestSignInLink({ username: string, redirectUri?: string })` ### Parameters #### Arguments - **username** (string) - Required - The username of the user requesting the magic link. - **redirectUri** (string) - Optional - The URI to redirect the user to after successful sign-in. ### Request Example ```javascript import { usePasswordless } from "amazon-cognito-passwordless-auth"; export default function YourComponent() { const { requestSignInLink } = usePasswordless();
{ requestSignInLink({ username: event.currentTarget.username.value, redirectUri: "https://example.com/article/45", }); event.preventDefault(); }} >
; } ``` ``` -------------------------------- ### Store and Retrieve Tokens Source: https://context7.com/aws-samples/amazon-cognito-passwordless-auth/llms.txt Low-level functions for persisting and reading authentication tokens from storage. These use Amplify-compatible keys, allowing interoperability with Amplify's token management. ```typescript import { storeTokens, retrieveTokens, } from "amazon-cognito-passwordless-auth/storage"; // ── Store tokens after a custom tokensCb ───────────────────────────────────── await storeTokens({ accessToken: "eyJra...", idToken: "eyJra...", refreshToken: "eyJjb...", expireAt: new Date(Date.now() + 3600 * 1000), }); // ── Retrieve tokens (e.g. for an authenticated API call) ───────────────────── const tokens = await retrieveTokens(); if (!tokens?.accessToken) { redirectToLogin(); } else { const response = await fetch("https://api.example.com/data", { headers: { Authorization: `Bearer ${tokens.accessToken}` }, }); } ``` -------------------------------- ### Configure Passwordless Authentication Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/react/README-REACT.md Import and configure the Passwordless library with your Cognito details and optional FIDO2 settings. This should be done in your web app's entry point. ```javascript import { Passwordless } from "amazon-cognito-passwordless-auth"; Passwordless.configure({ cognitoIdpEndpoint: "eu-west-1", // you can also use the full endpoint URL, potentially to use a proxy clientId: "", // optional, only required if you want to use FIDO2: fido2: { baseUrl: "", /** * all other FIDO2 config is optional, values below are examples only to illustrate what you might configure. * (this client side config is essentially an override, that's merged on top of the config received from the backend) */ authenticatorSelection: { userVerification: "required", requireResidentKey: true, residentKey: "preferred", authenticatorAttachment: "platform", }, rp: { id: "example.com", name: "Example", }, attestation: "direct", extensions: { appid: "u2f.example.com", credProps: true, hmacCreateSecret: true, }, timeout: 120000, }, userPoolId: "", // optional, only required if you want to use USER_SRP_AUTH // optional, additional headers that will be sent with each request to Cognito: proxyApiHeaders: { "
": "", "
": "", }, storage: localStorage, // Optional, default to localStorage }); ``` -------------------------------- ### Deploy Passwordless CDK Construct Source: https://context7.com/aws-samples/amazon-cognito-passwordless-auth/llms.txt Use the Passwordless CDK construct to provision backend resources for passwordless authentication flows. Configure enabled auth methods, allowed origins, and other settings as needed. ```typescript import * as cdk from "aws-cdk-lib"; import { Construct } from "constructs"; import { Passwordless } from "amazon-cognito-passwordless-auth/cdk"; export class AuthStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const passwordless = new Passwordless(this, "Passwordless", { // Bring your own User Pool, or omit to have one created: // userPool: existingPool, allowedOrigins: [ "https://app.example.com", "http://localhost:5173", ], magicLink: { sesFromAddress: "no-reply@auth.example.com", // verified SES identity sesRegion: "us-east-1", secondsUntilExpiry: cdk.Duration.minutes(15), minimumSecondsBetween: cdk.Duration.seconds(60), autoConfirmUsers: true, // auto-confirm on first sign-in }, fido2: { allowedRelyingPartyIds: ["app.example.com", "localhost"], relyingPartyName: "My App", userVerification: "required", attestation: "none", residentKey: "preferred", // enable passkeys authenticatorAttachment: "platform", enforceFido2IfAvailable: false, timeouts: { credentialRegistration: 300_000, // 5 min signIn: 120_000, // 2 min }, api: { addWaf: true, wafRateLimitPerIp: 100, throttlingBurstLimit: 1000, throttlingRateLimit: 2000, }, updatedCredentialsNotification: { sesFromAddress: "no-reply@auth.example.com", }, }, smsOtpStepUp: { otpLength: 6, // originationNumber: "+15005550006", // optional dedicated number }, clientMetadataTokenKeys: ["signInMethod"], // persist in ID token claims logLevel: "INFO", }); // Outputs used by the front-end: new cdk.CfnOutput(this, "UserPoolId", { value: passwordless.userPool.userPoolId, }); new cdk.CfnOutput(this, "ClientId", { value: passwordless.userPoolClients!.at(0)!.userPoolClientId, }); new cdk.CfnOutput(this, "Fido2Url", { value: passwordless.fido2Api!.url!, // e.g. https://abc123.execute-api.us-east-1.amazonaws.com/v1/ }); } } ``` -------------------------------- ### signInWithLink Source: https://context7.com/aws-samples/amazon-cognito-passwordless-auth/llms.txt Checks the current browser URL for a valid magic link fragment and, if found, completes the Cognito challenge automatically. Call this once on page load (or on each route change). Returns an object with a `signedIn` promise and an `abort` function. ```APIDOC ## Client: `signInWithLink` Checks the current browser URL for a valid magic link fragment and, if found, completes the Cognito challenge automatically. Call this once on page load (or on each route change). Returns `{ signedIn: Promise, abort: () => void }`. ```typescript import { signInWithLink } from "amazon-cognito-passwordless-auth/magic-link"; // ── Typical page-load handler ───────────────────────────────────────────────── const { signedIn } = signInWithLink({ statusCb: (status) => { // "CHECKING_FOR_SIGNIN_LINK" | "NO_SIGNIN_LINK" | "SIGNING_IN_WITH_LINK" // "SIGNED_IN_WITH_LINK" | "SIGNIN_LINK_EXPIRED" | "INVALID_SIGNIN_LINK" console.log("Magic link status:", status); }, tokensCb: async (tokens) => { // Fired on successful sign-in; tokens stored automatically if omitted localStorage.setItem("lastUser", tokens.username); }, }); const tokens = await signedIn; if (tokens) { console.log("Signed in via magic link as:", tokens.username); } else { console.log("No magic link in URL, render normal sign-in UI"); } ``` ``` -------------------------------- ### Wrap App with PasswordlessContextProvider Source: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/react/README-REACT.md Wrap your React application with PasswordlessContextProvider to manage authentication state and actions. This ensures authentication logic runs only once. ```typescript import { PasswordlessContextProvider } from "amazon-cognito-passwordless-auth/react"; ReactDOM.createRoot(document.getElementById("root")).render( ); ```