Skip to main content

MastraAuthWorkos class

The MastraAuthWorkos class provides authentication for Mastra using WorkOS. It verifies incoming requests using WorkOS access tokens and integrates with the Mastra server using the auth option.

Usage example
Direct link to Usage example

src/mastra/index.ts
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,
}),
},
})
note

You can omit the constructor parameters if you have the appropriately named environment variables (WORKOS_API_KEY and WORKOS_CLIENT_ID) set. In that case, use new MastraAuthWorkos() without any arguments.

Constructor parameters
Direct link to Constructor parameters

apiKey?:

string
= process.env.WORKOS_API_KEY
Your WorkOS API key. This is used to authenticate with the WorkOS API for user verification and organization management.

clientId?:

string
= process.env.WORKOS_CLIENT_ID
Your WorkOS Client ID. This identifies your application when exchanging authorization codes for access tokens.

name?:

string
= "workos"
Custom name for the auth provider instance.

redirectUri?:

string
= process.env.WORKOS_REDIRECT_URI
OAuth redirect URI used by WorkOS AuthKit. Set this when you use the built-in WorkOS sign-in flow.

fetchMemberships?:

boolean
= false
Loads organization memberships during authentication. Set this to `true` when you use `MastraFGAWorkos` so FGA checks can resolve the correct organization membership ID.

trustJwtClaims?:

boolean
= false
Trusts verified bearer-token claims enough to construct a `WorkOSUser` even when `workos.userManagement.getUser()` does not apply. Use this for service-account or machine-to-machine tokens backed by a WorkOS custom JWT template.

jwtClaims?:

{ userId?: string; workosId?: string; email?: string; name?: string; organizationId?: string; organizationMembershipId?: string }
Maps verified bearer JWT claims into the authenticated `WorkOSUser`. Useful for custom JWT templates that include `organizationMembershipId` or other FGA-specific claims.

Environment variables
Direct link to Environment variables

The following environment variables are automatically used when constructor options aren't provided:

WORKOS_API_KEY?:

string
Your WorkOS API key. Can be found in your WorkOS Dashboard under API Keys.

WORKOS_CLIENT_ID?:

string
Your WorkOS Client ID. Can be found in your WorkOS Dashboard under Applications.

WORKOS_REDIRECT_URI?:

string
OAuth redirect URI used by WorkOS AuthKit when you use the built-in session-based flow.

Default authorization behavior
Direct link to Default authorization behavior

By default, MastraAuthWorkos authorizes any authenticated WorkOS user whose resolved user object includes both id and workosId.

  1. Token Verification: The access token is verified with WorkOS to ensure it's valid and not expired
  2. User Retrieval: User information is extracted from the verified token
  3. Authorization Decision: Access is granted if the resolved user contains the required identifiers

This means that by default, MastraAuthWorkos acts as an authentication provider rather than a role gate.

FGA membership loading
Direct link to FGA membership loading

Set fetchMemberships: true when you use MastraFGAWorkos. This loads the user's WorkOS organization memberships during authentication so FGA checks can resolve the correct organization membership ID.

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

Service tokens and JWT claims
Direct link to Service tokens and JWT claims

If your WorkOS JWT template includes custom claims, you can map them directly into the authenticated WorkOSUser.

src/mastra/auth.ts
import { MastraAuthWorkos } from '@mastra/auth-workos'

const auth = 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',
},
})

When trustJwtClaims is enabled, Mastra can authenticate verified bearer tokens for service principals even if getUser() is not the right lookup path. This is the preferred way to pass pre-resolved organizationMembershipId values into FGA checks for machine-to-machine flows.

Custom authorization
Direct link to Custom authorization

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

src/mastra/auth.ts
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'
}
}

WorkOS user type
Direct link to WorkOS user type

The WorkOSUser type available inside authorizeUser() and other WorkOS auth hooks includes Mastra's normalized user fields plus WorkOS-specific metadata. WorkOS also allows administrators to set up custom JWT templates, so the exact structure may vary based on your configuration. The following example shows what a WorkOS-backed user object might look like:

{
'urn:myapp:full_name': 'John Doe',
'urn:myapp:email': 'john.doe@example.com',
'urn:myapp:organization_tier': 'bronze',
'urn:myapp:user_language': 'en',
'urn:myapp:organization_domain': 'example.com',
iss: 'https://api.workos.com/user_management/client_01ABC123DEF456GHI789JKL012',
sub: 'user_01XYZ789ABC123DEF456GHI012',
sid: 'session_01PQR456STU789VWX012YZA345',
jti: '01MNO678PQR901STU234VWX567',
org_id: 'org_01DEF234GHI567JKL890MNO123',
role: 'member',
roles: [ 'member' ],
permissions: [],
exp: 1758290589,
iat: 1758290289
}

The properties with urn:myapp: prefixes are custom claims configured in your WorkOS JWT template. Standard JWT claims include sub (user ID), iss (issuer), exp (expiration), and WorkOS-specific claims like org_id, role, and roles.

MastraAuthWorkos Class