WorkOS Authentication for Mastra Server

Trust: ★★★☆☆ (0.90) · 0 validations · developer_reference

Published: 2026-05-10 · Source: crawler_authoritative

Tình huống

Guide for integrating WorkOS authentication into Mastra server using the @mastra/auth-workos package, targeting Node.js/TypeScript developers building authenticated applications.

Insight

The @mastra/auth-workos package provides WorkOS-based authentication for Mastra by verifying incoming requests using WorkOS access tokens. It integrates via the auth option in the Mastra server configuration. The package supports basic usage with environment variables (WORKOS_API_KEY, WORKOS_CLIENT_ID), custom configuration with explicit options, and FGA membership loading via fetchMemberships: true flag when used alongside MastraFGAWorkos. Default authorization grants access to any authenticated WorkOS user when the resolved user object contains both a Mastra user ID and a WorkOS user ID. Service tokens and machine-to-machine access are supported through trustJwtClaims: true with custom jwtClaims configuration that can include organizationId and organizationMembershipId fields. Custom authorization can be implemented by subclassing MastraAuthWorkos and overriding the authorizeUser() method. The package supports React, cURL, and other clients that include the WorkOS access token as a Bearer token in the Authorization header.

Hành động

  1. Create a WorkOS account and configure an Application with redirect URIs and allowed origins.
  2. Set environment variables: WORKOS_API_KEY, WORKOS_CLIENT_ID, and optionally WORKOS_REDIRECT_URI.
  3. Install the package: npm install @mastra/auth-workos@latest (also supports pnpm, yarn, bun).
  4. Configure MastraAuthWorkos in your Mastra server config via server.auth option.
  5. For basic usage: new MastraAuthWorkos() loads credentials from environment.
  6. For custom config: pass apiKey, clientId, and other options directly to the constructor.
  7. For FGA integration: set fetchMemberships: true and configure MastraFGAWorkos alongside.
  8. For service tokens: enable trustJwtClaims: true and specify jwtClaims for organization context.
  9. Client-side: install @workos-inc/node, exchange authorization code for access token using workos.userManagement.authenticateWithCode(), then include the token as Bearer <accessToken> in MastraClient Authorization header.

Kết quả

Mastra verifies incoming requests using WorkOS access tokens. Authenticated requests include a verified WorkOS user with Mastra user ID. When fetchMemberships is enabled, organization memberships are loaded for FGA authorization checks. Custom JWT templates with trustJwtClaims enabled allow service accounts to bypass user lookup while preserving FGA context from verified token claims.

Điều kiện áp dụng

Requires @mastra/auth-workos package. When using FGA features, also requires @mastra/auth-workos for MastraFGAWorkos. Works with Node.js-based Mastra server deployments. Custom JWT template approach requires WorkOS Custom JWT Templates configuration.


Nội dung gốc (Original)

WorkOS

The @mastra/auth-workos package provides authentication for Mastra using WorkOS. It verifies incoming requests using WorkOS access tokens and integrates with the Mastra server using the auth option.

Prerequisites

This example uses WorkOS authentication. Make sure to:

  1. Create a WorkOS account at workos.com
  2. Set up an Application in your WorkOS Dashboard
  3. Configure your redirect URIs and allowed origins
  4. Set up Organizations and configure user roles as needed
WORKOS_API_KEY=sk_live_...
WORKOS_CLIENT_ID=client_...

Note: You can find your API key and Client ID in the WorkOS Dashboard under API Keys and Applications respectively.

For detailed setup instructions, refer to the WorkOS documentation for your specific platform.

Installation

Before you can use the MastraAuthWorkos class you have to install the @mastra/auth-workos package.

npm:

npm install @mastra/auth-workos@latest

pnpm:

pnpm add @mastra/auth-workos@latest

Yarn:

yarn add @mastra/auth-workos@latest

Bun:

bun add @mastra/auth-workos@latest

Usage examples

Basic usage with environment variables

import { Mastra } from '@mastra/core'
import { MastraAuthWorkos } from '@mastra/auth-workos'
 
export const mastra = new Mastra({
  server: {
    auth: new MastraAuthWorkos(),
  },
})

Custom configuration

import { Mastra } from '@mastra/core'
import { MastraAuthWorkos } from '@mastra/auth-workos'
 
export const mastra = new Mastra({
  server: {
    auth: new MastraAuthWorkos({
      apiKey: process.env.WORKOS_API_KEY,
      clientId: process.env.WORKOS_CLIENT_ID,
    }),
  },
})

Configuration

Default authorization

By default, MastraAuthWorkos grants access to any authenticated WorkOS user. The authorization check succeeds when the resolved user object contains both a Mastra user ID and a WorkOS user ID.

FGA membership loading

Set fetchMemberships: true when you use MastraFGAWorkos. This tells the auth provider to load the user’s WorkOS organization memberships during authentication so FGA checks can resolve the correct organization membership ID.

import { MastraAuthWorkos, MastraFGAWorkos } from '@mastra/auth-workos'
 
const workosAuth = new MastraAuthWorkos({
  apiKey: process.env.WORKOS_API_KEY,
  clientId: process.env.WORKOS_CLIENT_ID,
  fetchMemberships: true,
})
 
const workosFga = new MastraFGAWorkos({
  apiKey: process.env.WORKOS_API_KEY,
  clientId: process.env.WORKOS_CLIENT_ID,
})

When fetchMemberships is false, Mastra skips the extra WorkOS listOrganizationMemberships() call on each authenticated request.

Service tokens and custom JWT templates

For machine-to-machine or service-account access, you can configure MastraAuthWorkos to trust verified bearer-token claims from a WorkOS custom JWT template.

import { MastraAuthWorkos } from '@mastra/auth-workos'
 
const workosAuth = new MastraAuthWorkos({
  apiKey: process.env.WORKOS_API_KEY,
  clientId: process.env.WORKOS_CLIENT_ID,
  redirectUri: process.env.WORKOS_REDIRECT_URI,
  trustJwtClaims: true,
  jwtClaims: {
    organizationId: 'org_id',
    organizationMembershipId: 'urn:mastra:organization_membership_id',
  },
})

This is useful when your JWT template already includes the exact FGA context Mastra needs, such as organizationMembershipId, tenant IDs, or service-principal identifiers. When trustJwtClaims is enabled, Mastra can fall back to those verified claims if a bearer token is not meant to round-trip through workos.userManagement.getUser().

Custom authorization

If you need stricter authorization, subclass MastraAuthWorkos and override authorizeUser():

import { MastraAuthWorkos } from '@mastra/auth-workos'
import type { HonoRequest } from 'hono'
 
class AdminOnlyWorkosAuth extends MastraAuthWorkos {
  async authorizeUser(user: any, _request: HonoRequest): Promise<boolean> {
    return user?.metadata?.role === 'admin'
  }
}
 
const workosAuth = new AdminOnlyWorkosAuth({
  apiKey: process.env.WORKOS_API_KEY,
  clientId: process.env.WORKOS_CLIENT_ID,
})

Info: Visit MastraAuthWorkos for all available configuration options.

Client-side setup

When using WorkOS auth, you’ll need to implement the WorkOS authentication flow to exchange an authorization code for an access token, then use that token with your Mastra requests.

Installing WorkOS SDK

First, install the WorkOS SDK in your application:

npm:

npm install @workos-inc/node

pnpm:

pnpm add @workos-inc/node

Yarn:

yarn add @workos-inc/node

Bun:

bun add @workos-inc/node

Exchanging code for access token

After users complete the WorkOS authentication flow and return with an authorization code, exchange it for an access token:

import { WorkOS } from '@workos-inc/node'
 
const workos = new WorkOS(process.env.WORKOS_API_KEY)
 
export const authenticateWithWorkos = async (code: string, clientId: string) => {
  const authenticationResponse = await workos.userManagement.authenticateWithCode({
    code,
    clientId,
  })
 
  return authenticationResponse.accessToken
}

Note: Refer to the WorkOS User Management documentation for more authentication methods and configuration options.

Configuring MastraClient

When auth is enabled, all requests made with MastraClient must include a valid WorkOS access token in the Authorization header:

import { MastraClient } from '@mastra/client-js'
 
export const createMastraClient = (accessToken: string) => {
  return new MastraClient({
    baseUrl: 'https://<mastra-api-url>',
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
  })
}

Info: The access token must be prefixed with Bearer in the Authorization header.

Visit Mastra Client SDK for more configuration options.

Making authenticated requests

Once MastraClient is configured with the WorkOS access token, you can send authenticated requests:

React:

import { WorkOS } from '@workos-inc/node'
import { MastraClient } from '@mastra/client-js'
 
const workos = new WorkOS(process.env.WORKOS_API_KEY)
 
export const callMastraWithWorkos = async (code: string, clientId: string) => {
  const authenticationResponse = await workos.userManagement.authenticateWithCode({
    code,
    clientId,
  })
 
  const token = authenticationResponse.accessToken
 
  const mastra = new MastraClient({
    baseUrl: 'http://localhost:4111',
    headers: {
      Authorization: `Bearer ${token}`,
    },
  })
 
  const weatherAgent = mastra.getAgent('weatherAgent')
  const response = await weatherAgent.generate("What's the weather like in Nairobi")
 
  return response.text
}

cURL:

curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <your-workos-access-token>" \
  -d '{
    "messages": "Weather in London"
  }'

Liên kết