/
Contact usSee pricingStart building
Node
​

    About Stytch

    Introduction
    Integration Approaches
      Full-stack overview
      Frontend (pre-built UI)
      Frontend (headless)
      Backend
    Migrations
      Migration overview
      Migrating users statically
      Migrating users dynamically
      Additional migration considerations
      Zero-downtime deployment
      Defining external IDs for users
      Migrating from Stytch Consumer to B2B
      Exporting from Stytch
    Custom Domains
      Overview

    Authentication

    DFP Protected Auth
      Overview
      Setting up DFP Protected Auth
      Handling challenges
    Magic Links
    • Email Magic Links

      • Getting started with the API
        Getting started with the SDK
        Replacing your password reset flow
        Building an invite user flow
        Add magic links to an existing auth flow
        Adding PKCE to a Magic Link flow
        Magic Link redirect routing
    • Embeddable Magic Links

      • Getting started with the API
    MFA
      Overview
      Backend integration
      Frontend integration
      Remembered device flow
    Mobile Biometrics
      Overview
    M2M Authentication
      Authenticate an M2M Client
      Rotate client secrets
      Import M2M Clients from Auth0
    OAuth
    • Identity providers

      • Overview
        Provider setup
      Getting started with the API (Google)
      Add Google One Tap via the SDK
      Email address behavior
      Adding PKCE to an OAuth flow
    Connected Apps
      Overview
      Getting started with the SDK
      Client types
      OAuth scopes
    • Integration Guides

      • MCP Authorization Overview
        Integrate with MCP servers deployed on Cloudflare
        Integrate with MCP servers on Vercel
        Integrate with CLI Apps
        Integrate with AI agents
    • Resources

      • Consent Management
    Passcodes
      Getting started with the API
      Getting started with the SDK
    • Toll fraud

      • What is SMS toll fraud?
        How you can prevent toll fraud
      Unsupported countries
    Passkeys & WebAuthn
    • Passkeys

      • Passkeys overview
        Set up Passkeys with the frontend SDK
    • WebAuthn

      • Getting started with the API
        Getting started with the SDK
    Passwords
      Getting started with the API
      Getting started with the SDK
      Password strength policy
    • Email verification

      • Overview
        Email verification before password creation
        Email verification after password creation
    Sessions
      How to use sessions
      Backend integrations
      Frontend integrations
      Custom claims
      Custom claim templates
      Session tokens vs JWTs
      How to use Stytch JWTs
    TOTP
      Getting started with the API
      Getting started with the SDK
    Web3
      Getting started with the API
      Getting started with the SDK
    Trusted Auth Tokens
      Overview
      Getting Started with External IDPs
      Getting Started with Custom Auth Factors
    Device History
      New Device Notifications

    RBAC

    Resources
      Overview
      Role assignment
    Integration Guides
      Start here
      Backend integration
      Headless frontend integration
      (Legacy) Implement RBAC with metadata

    3rd Party Integrations

    Planetscale
    Supabase
    Feathery
    Unit

    Testing

    E2E testing
    Sandbox values
Get support on SlackVisit our developer forum

Contact us

Consumer Authentication

/

Guides

/

Authentication

/

Trusted Auth Tokens

/

Getting Started with Custom Auth Factors

Accepting Custom Auth Factors

The Trusted Auth Tokens feature allows developers to attest end-user identities by exchanging signed JWTs for Stytch sessions. Usually, your existing identity infrastructure will provide a JWT that can be used for this purpose such as an access_token or id_token. Stytch will use the JWKS endpoint hosted by your existing infrastructure to validate these JWTs and provision users automatically as required -- no additional setup is needed.

If your identity infrastructure does not provide a JWT, you can create your own JWT using a private key, as demonstrated below.

You can also use this technique to wrap authentication factors that Stytch does not natively support, such as PINs or push-based authentication factor apps like Cisco Duo.

Generating a Public-Private Keypair

Use a library such as OpenSSL to generate an RSA public-private keypair. The public key can be added to your Trusted Auth Token profile in the Stytch dashboard here (in the JWKS URL row, click "Use public keys instead"). The private key should be kept secret, and exposed to your application using an environment variable. It is often useful to base64 encode the private key for easy addition to .env files.

# Generate private key
openssl genrsa -out "private_key.pem" 2048
# Extract public key
openssl rsa -in "private_key.pem" -pubout -out "public_key.pem"
# Base64 encode the private key
base64 < ./private_key.pem

Creating and Signing a JWT

Use any compatible JWT library to sign your JWT with your private key. Here is an example using jose, a popular library in the Node ecosystem. Be sure to set the iss and aud claims to match the issuer and audience configured in your Trusted Auth Token Profile. Choose a short expiry for the JWT - 5 minutes is a good default.

Other claims (email, sub, role_ids, jti, etc... ) should be set according to your previously configured attribute mapping. Remember, an email and a token ID are required. All other fields are optional.

import { importPKCS8, SignJWT } from 'jose';
import { randomBytes } from 'node:crypto';

async function createJWT({email, role_assignments, user_id, token_id}) {
  // Expose the private key as an environment variable
  // If you base64 encoded it before, remember to decode it here as well
  const privateKeyString = Buffer.from(process.env.PRIVATE_KEY, 'base64')
    .toString('utf8').trim();
  const privateKey = await importPKCS8(privateKeyString, 'RS256');

  // details to encode in the token
  const claims = {
    // Required - the user's email address
    'email': email,
    // Optional - RBAC roles to assign to the user
    'assignments': role_assignments,
  };
  
  // Required - a token ID used to uniquely identify the credential
  // This can be defined by your application or a random string
  const tokenID = token_id || randomBytes(30).toString('base64');
  
  const jwt = await new SignJWT(claims)
    .setProtectedHeader({ alg: 'RS256' })
    .setIssuedAt()
    .setSubject(user_id) // sub claim, used as the user's external ID
    .setJti(tokenID)
    .setIssuer('https://auth.example.com') // iss claim
    .setAudience('https://api.example.com') // aud claim
    .setExpirationTime('5 minutes') // token expiration time
    .sign(privateKey);

  return jwt;
};

createJWT({
  email: 'ada.lovelace@example.com',
  role_assignments: ['editor', 'reader'],
  user_id: 'user_123456'
}).then(jwt => console.log(jwt))

Logging a user in

After you have minted your JWT, call the Attest Session API endpoint to exchange the JWT for a Stytch Session.

const stytch = require('stytch');

const client = new stytch.Client({
  project_id: 'PROJECT_ID',
  secret: 'SECRET',
});

createJWT({
  email: 'ada.lovelace@example.com',
  role_assignments: ['editor', 'reader'],
  user_id: 'user_123456'
})
  .then(jwt => {
    const params = {
      profile_id: "trusted-auth-token-profile-test-41920359-8bbb-4fe8-8fa3-aaa83f35f02c",
      token: "eyJhb...",
    };
    
    return client.sessions.attest(params)
  })
  .then(resp => {
    console.log(resp)
  })
  .catch(err => {
    console.log(err)
  });

Supporting Custom Auth Factors

Call the Attest Session API endpoint with a session_token or session_jwt to attach the attestation to an existing session instead of creating a new one. It may be useful to pass in a unique token_id to the JWT to tie the custom authentication factor you validated to the session for later reference.

validateCustomFactor()
  .then(validation => createJWT({
    email: 'ada.lovelace@example.com',
    role_assignments: ['editor', 'reader'],
    user_id: 'user_123456',
    // ID of the validation event - will be passed to the Stytch session as
    // trusted_auth_token_factor.token_id
    token_id: validation.validation_id,
  }))
  .then(jwt => {
    const params = {
      profile_id: "trusted-auth-token-profile-test-41920359-8bbb-4fe8-8fa3-aaa83f35f02c",
      token: "eyJhb...",
      // Pass a session token in to add your custom factor to an existing session
      session_token: "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q",
    };
    
    return client.sessions.attest(params)
  })
  .then(resp => {
    console.log(resp)
  })
  .catch(err => {
    console.log(err)
  });

Generating a Public-Private Keypair

Creating and Signing a JWT

Logging a user in

Supporting Custom Auth Factors