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

MastraAuthNeon and MastraRBACNeon

MastraAuthNeon connects Mastra authentication to Neon Auth. It authenticates JWT bearer tokens with Neon Auth's JWKS endpoint and falls back to validating Neon Auth session cookies through its session API. The provider also supports email-and-password sign-in, sign-up, and session management.

MastraRBACNeon maps Neon Auth organization roles to Mastra permissions. Register it separately when your application uses Neon Auth organization memberships for role-based access control.

Usage
Usage的直接链接

src/mastra/index.ts
import { Mastra } from '@mastra/core/mastra'
import { MastraAuthNeon, MastraRBACNeon } from '@mastra/auth-neon'

const auth = new MastraAuthNeon()

const rbac = new MastraRBACNeon({
roleMapping: {
admin: ['*'],
member: ['agents:read', 'workflows:read'],
_default: [],
},
})

export const mastra = new Mastra({
server: {
auth,
rbac,
},
})

Set NEON_AUTH_BASE_URL to your Neon Auth service URL. You can also pass baseUrl directly to both constructors.

MastraAuthNeon
mastraauthneon的直接链接

Constructor parameters
Constructor parameters的直接链接

The MastraAuthNeon constructor accepts an optional MastraAuthNeonOptions object.

baseUrl?:

string
Neon Auth service URL. Falls back to the NEON_AUTH_BASE_URL environment variable. Trailing slashes are removed.

jwksUrl?:

string
JWKS endpoint used to verify bearer tokens. Falls back to NEON_AUTH_JWKS_URL, then <baseUrl>/auth/jwks.

sessionCookieName?:

string
Name of the Neon Auth session cookie. Defaults to neonauth.session_token.

signUpEnabled?:

boolean
Whether credentials-based sign-up is enabled. Defaults to true.

name?:

string
Provider name. Defaults to neon.

authorizeUser?:

AuthorizeUserFn<NeonAuthUser>
Custom authorization function called after authentication.

mapUserToResourceId?:

(user: NeonAuthUser) => string | undefined | null
Maps an authenticated user to a Mastra memory resource ID.

protected?:

MastraAuthConfig['protected']
Routes that require authentication.

public?:

MastraAuthConfig['public']
Routes that do not require authentication.

Environment variables
Environment variables的直接链接

NEON_AUTH_BASE_URL:

string
Default Neon Auth service URL when baseUrl is not passed to the constructor.

NEON_AUTH_JWKS_URL:

string
Default JWKS endpoint when jwksUrl is not passed to the constructor.

Authentication methods
Authentication methods的直接链接

authenticateToken()
authenticatetoken的直接链接

await auth.authenticateToken(token, request)

Verifies the token as a JWT with the configured JWKS endpoint. If JWT verification fails, the provider validates it as a Neon Auth session token through the session API. Returns the authenticated NeonAuthUser, or null when neither method succeeds.

authorizeUser()
authorizeuser的直接链接

await auth.authorizeUser(user, request)

Runs the configured custom authorization function when one is provided. Otherwise, it requires a Neon Auth user ID and rejects expired JWT payloads.

Credentials methods
Credentials methods的直接链接

signIn()
signin的直接链接

const result = await auth.signIn(email, password, request)

Authenticates email-and-password credentials through Neon Auth. Returns the authenticated user, optional token, and response cookies.

signUp()
signup的直接链接

const result = await auth.signUp(email, password, name, request)

Creates a Neon Auth account using email-and-password credentials. name is optional; when omitted, the provider derives a display name from the email address. Returns the authenticated user, optional token, and response cookies.

isSignUpEnabled()
issignupenabled的直接链接

const enabled = auth.isSignUpEnabled()

Returns the configured signUpEnabled value.

Session methods
Session methods的直接链接

createSession()
createsession的直接链接

const session = await auth.createSession(userId, metadata)

Creates a normalized Mastra session with a generated ID and a seven-day expiration without creating a remote Neon Auth session.

validateSession()
validatesession的直接链接

const session = await auth.validateSession(sessionId)

Validates a Neon Auth session token and returns a normalized Mastra session, or null when the session is invalid.

refreshSession()
refreshsession的直接链接

const session = await auth.refreshSession(sessionId)

Validates the session through Neon Auth. Neon Auth refreshes sessions automatically when its configured update interval is reached.

destroySession()
destroysession的直接链接

await auth.destroySession(sessionId)

Completes without a remote request. Neon Auth handles session destruction through its sign-out endpoint, while getClearSessionHeaders() returns the headers used to clear local session cookies.

MastraRBACNeon
mastrarbacneon的直接链接

Constructor parameters
Constructor parameters的直接链接

The MastraRBACNeon constructor accepts a MastraRBACNeonOptions object.

roleMapping:

RoleMapping
Maps Neon Auth role names to Mastra permission patterns. Use _default to define permissions for unmapped roles.

baseUrl?:

string
Neon Auth service URL. Falls back to the NEON_AUTH_BASE_URL environment variable. Trailing slashes are removed.

organizationId?:

string
Restricts membership lookup to one Neon Auth organization.

getUserRoles?:

(user: NeonAuthUser) => Promise<string[]> | string[]
Custom function for extracting role names. When omitted, the provider fetches organization memberships from Neon Auth.

cache?:

{ ttlMs?: number; maxSize?: number }
Role lookup cache configuration. The defaults are 60,000 ms and 1,000 entries.

Methods
Methods的直接链接

getRoles()
getroles的直接链接

const roles = await rbac.getRoles(user)

Returns roles from the configured getUserRoles function, the user's JWT role claim, or Neon Auth organization memberships. When organizationId is set, only memberships for that organization are considered.

hasRole()
hasrole的直接链接

const allowed = await rbac.hasRole(user, 'admin')

Checks whether the user has the requested role.

getPermissions()
getpermissions的直接链接

const permissions = await rbac.getPermissions(user)

Resolves the user's roles through roleMapping and returns Mastra permission patterns.

hasPermission()
haspermission的直接链接

const allowed = await rbac.hasPermission(user, 'agents:read')

Checks whether the resolved permissions allow the requested permission.

hasAllPermissions() and hasAnyPermission()
hasallpermissions-and-hasanypermission的直接链接

const canReadAndRun = await rbac.hasAllPermissions(user, ['agents:read', 'agents:execute'])
const canReadAnything = await rbac.hasAnyPermission(user, ['agents:read', 'workflows:read'])

Checks whether the user has all or at least one of the requested permissions.

getAvailableRoles()
getavailableroles的直接链接

const roles = await rbac.getAvailableRoles()

Returns the configured role names except _default.

getRolePermissions()
getrolepermissions的直接链接

const permissions = await rbac.getRolePermissions('member')

Resolves the permission patterns configured for a role.