MastraAuthGoogle and MastraRBACGoogle class
MastraAuthGoogle classMastraAuthGoogle class的直接链接
The MastraAuthGoogle class provides authentication for Mastra using Google Workspace. It implements an OAuth 2.0 / OIDC login flow with encrypted session cookies and verifies Google ID tokens. It integrates with the Mastra server through the auth option.
Usage exampleUsage example的直接链接
import { Mastra } from '@mastra/core'
import { MastraAuthGoogle } from '@mastra/auth-google'
export const mastra = new Mastra({
server: {
auth: new MastraAuthGoogle({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
redirectUri: process.env.GOOGLE_REDIRECT_URI,
allowedDomains: ['example.com'],
}),
},
})
You can omit the constructor parameters if the required environment variables are set. In that case, use new MastraAuthGoogle() without any arguments.
Constructor parametersConstructor parameters的直接链接
clientId?:
clientSecret?:
redirectUri?:
scopes?:
allowedDomains?:
hd claim.hostedDomain?:
hd. This is a hint only and is not used for authorization.session?:
cookieName?:
cookieMaxAge?:
cookiePassword?:
secureCookies?:
Secure flag on session cookies.name?:
Environment variablesEnvironment variables的直接链接
The following environment variables are automatically used when constructor options aren't provided:
GOOGLE_CLIENT_ID:
GOOGLE_CLIENT_SECRET?:
GOOGLE_REDIRECT_URI?:
GOOGLE_COOKIE_PASSWORD?:
GOOGLE_ALLOWED_DOMAINS?:
GOOGLE_HOSTED_DOMAIN?:
Authentication flowAuthentication flow的直接链接
MastraAuthGoogle authenticates requests in the following order:
- Session cookie. With SSO enabled, the provider reads and decrypts the encrypted session cookie. A valid, unexpired session authenticates the user.
- Google ID token fallback: If no valid session cookie is present, verifies the
Authorizationheader token against Google's JWKS endpoint.
After authentication, authorizeUser checks that the user has a valid Google user ID, the token-derived expiration hasn't passed, and the user's verified hd claim matches allowedDomains when domains are configured.
Authentication methodsAuthentication methods的直接链接
authenticateToken(token, request?)authenticatetokentoken-request的直接链接
Authenticates a Google ID token. When SSO is enabled, this method checks the encrypted session cookie before it verifies the Bearer token.
const user = await auth.authenticateToken(idToken, request)
Returns: Promise<GoogleUser | null>
getCurrentUser(request)getcurrentuserrequest的直接链接
Returns the authenticated user from a session cookie or Bearer Google ID token.
const user = await auth.getCurrentUser(request)
Returns: Promise<GoogleUser | null>
authorizeUser(user)authorizeuseruser的直接链接
Returns true when the user has an ID, hasn't expired, and matches allowedDomains when domains are configured.
const allowed = auth.authorizeUser(user)
Returns: boolean
getUser(userId)getuseruserid的直接链接
Returns null. Google ID tokens are verified directly, so this provider doesn't perform user lookup by ID.
const user = await auth.getUser(userId)
Returns: Promise<GoogleUser | null>
GoogleUser typegoogleuser-type的直接链接
The GoogleUser type extends the base EEUser interface with Google-specific fields:
id:
sub claim.googleId:
email?:
name?:
avatarUrl?:
hostedDomain?:
hd claim.expiresAt?:
emailVerified?:
groups?:
MastraRBACGoogle classMastraRBACGoogle class的直接链接
The MastraRBACGoogle class maps Google Workspace groups to Mastra permissions. It fetches user groups from the Google Admin SDK Directory API and resolves them against a configurable role mapping. Use it with MastraAuthGoogle or any other auth provider.
RBAC requires a valid Enterprise Edition license. It works without a license in development so you can try it locally, but you'll need a license for production. Contact sales for more information.
Usage exampleUsage example的直接链接
Use MastraRBACGoogle alongside an auth provider by passing it to the rbac option:
import { Mastra } from '@mastra/core'
import { MastraAuthGoogle, MastraRBACGoogle } from '@mastra/auth-google'
export const mastra = new Mastra({
server: {
auth: new MastraAuthGoogle(),
rbac: new MastraRBACGoogle({
serviceAccount: {
clientEmail: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL!,
privateKey: process.env.GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY!,
subject: process.env.GOOGLE_WORKSPACE_ADMIN_EMAIL!,
},
roleMapping: {
'admins@example.com': ['*'],
'engineering@example.com': ['agents:*', 'workflows:*', 'tools:*'],
'viewers@example.com': ['agents:read', 'workflows:read'],
_default: [],
},
}),
},
})
To use Google Workspace RBAC with a different auth provider, pass a getUserKey function to resolve the Google Directory API user key from the other provider's user object:
import { Mastra } from '@mastra/core'
import { MastraAuthAuth0 } from '@mastra/auth-auth0'
import { MastraRBACGoogle } from '@mastra/auth-google'
export const mastra = new Mastra({
server: {
auth: new MastraAuthAuth0(),
rbac: new MastraRBACGoogle({
getUserKey: user => user.email,
serviceAccount: {
clientEmail: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL!,
privateKey: process.env.GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY!,
subject: process.env.GOOGLE_WORKSPACE_ADMIN_EMAIL!,
},
roleMapping: {
'engineering@example.com': ['agents:*', 'workflows:*'],
'admins@example.com': ['*'],
_default: [],
},
}),
},
})
Constructor parametersConstructor parameters的直接链接
roleMapping:
'_default' to assign permissions to users who do not match any group. Supports wildcards like '*' (full access) and 'agents:*' (all agent actions).accessToken?:
getAccessToken?:
serviceAccount?:
clientEmail:
privateKey:
\n values from .env files are supported.privateKeyId?:
subject?:
scopes?:
getUserKey?:
userKey from an authenticated user. Defaults to user.email.mapGroupToRoles?:
[group.email].cache?:
maxSize?:
ttlMs?:
RBAC methodsRBAC methods的直接链接
getRoles(user)getrolesuser的直接链接
Returns Google Workspace group role IDs for a user.
const roles = await rbac.getRoles(user)
Returns: Promise<string[]>
getPermissions(user)getpermissionsuser的直接链接
Returns Mastra permissions resolved from Google Workspace groups and roleMapping.
const permissions = await rbac.getPermissions(user)
Returns: Promise<string[]>
hasPermission(user, permission)haspermissionuser-permission的直接链接
Checks whether a user has a permission.
const canReadAgents = await rbac.hasPermission(user, 'agents:read')
Returns: Promise<boolean>
hasRole(user, role)hasroleuser-role的直接链接
Checks whether a user resolved to a specific Google Workspace group role.
const isAdmin = await rbac.hasRole(user, 'admins@example.com')
Returns: Promise<boolean>
hasAllPermissions(user, permissions)hasallpermissionsuser-permissions的直接链接
Checks whether a user has every requested permission.
const canManageAgents = await rbac.hasAllPermissions(user, ['agents:read', 'agents:update'])
Returns: Promise<boolean>
hasAnyPermission(user, permissions)hasanypermissionuser-permissions的直接链接
Checks whether a user has at least one requested permission.
const canReadSomething = await rbac.hasAnyPermission(user, ['agents:read', 'workflows:read'])
Returns: Promise<boolean>
getAvailableRoles()getavailableroles的直接链接
Returns the role IDs configured in roleMapping, excluding _default.
const roles = await rbac.getAvailableRoles()
Returns: Promise<{ id: string; name: string }[]>
getPermissionsForRole(roleId)getpermissionsforroleroleid的直接链接
Returns the permissions configured for a role ID.
const permissions = await rbac.getPermissionsForRole('engineering@example.com')
Returns: Promise<string[]>
clearCache()clearcache的直接链接
Clears all cached Google Workspace group lookups.
rbac.clearCache()
Returns: void
clearUserCache(userKey)clearusercacheuserkey的直接链接
Clears the cached group lookup for one Directory API user key, such as an email address.
rbac.clearUserCache('user@example.com')
Returns: void
getCacheStats()getcachestats的直接链接
Returns the current group lookup cache size and maximum size.
const stats = rbac.getCacheStats()
Returns: { size: number; maxSize: number }
Additional configurationAdditional configuration的直接链接
MastraRBACGoogle uses GET https://admin.googleapis.com/admin/directory/v1/groups?userKey=... and handles pagination. Provide a service account with domain-wide delegation for production Google Workspace deployments, or pass accessToken / getAccessToken if your application already manages Google API tokens.
If user.groups is already an array, MastraRBACGoogle uses that value and doesn't call the Directory API. An empty groups array means the user has no Google group roles and resolves to _default permissions when _default is configured.
MastraRBACGoogle doesn't automatically read service-account environment variables. Pass service-account credentials through the serviceAccount option, or pass accessToken / getAccessToken.