跳到主要内容
非官方简体中文翻译,内容版权归 Mastra 所有,遵循 Apache-2.0 许可。

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
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,
}),
},
})
备注

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

Constructor parameters
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
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
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

MastraAuthWorkos acts as an authentication provider rather than a role gate by default.

FGA membership loading
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
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() isn't 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
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
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