MastraAuthGoogle & MastraRBACGoogle class
MastraAuthGoogle classDirect link to MastraAuthGoogle class
The MastraAuthGoogle class provides authentication for Mastra using Google Workspace. It implements an OAuth 2.0 / OIDC login flow with encrypted session cookies, verifies Google ID tokens, and integrates with the Mastra server using the auth option.
Usage exampleDirect link to Usage 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 you have the appropriately named environment variables set. In that case, use new MastraAuthGoogle() without any arguments.
Constructor parametersDirect link to Constructor parameters
clientId?:
clientSecret?:
redirectUri?:
scopes?:
allowedDomains?:
hostedDomain?:
session?:
cookieName?:
cookieMaxAge?:
cookiePassword?:
secureCookies?:
name?:
Environment variablesDirect link to Environment 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 flowDirect link to Authentication flow
MastraAuthGoogle authenticates requests in the following order:
- Session cookie: When SSO is enabled, reads the encrypted session cookie and decrypts it. If the session is valid and not expired, the user is authenticated.
- 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 has not passed, and the user's verified hd claim matches allowedDomains when domains are configured.
Authentication methodsDirect link to Authentication methods
authenticateToken(token, request?)Direct link to 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)Direct link to 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)Direct link to authorizeuseruser
Returns true when the user has an ID, has not expired, and matches allowedDomains when domains are configured.
const allowed = auth.authorizeUser(user)
Returns: boolean
getUser(userId)Direct link to getuseruserid
Returns null. Google ID tokens are verified directly, so this provider does not perform user lookup by ID.
const user = await auth.getUser(userId)
Returns: Promise<GoogleUser | null>
GoogleUser typeDirect link to googleuser-type
The GoogleUser type extends the base EEUser interface with Google-specific fields:
id:
googleId:
email?:
name?:
avatarUrl?:
hostedDomain?:
expiresAt?:
emailVerified?:
groups?:
MastraRBACGoogle classDirect link to MastraRBACGoogle 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 exampleDirect link to Usage 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 parametersDirect link to Constructor parameters
roleMapping:
accessToken?:
getAccessToken?:
serviceAccount?:
clientEmail:
privateKey:
privateKeyId?:
subject?:
scopes?:
getUserKey?:
mapGroupToRoles?:
cache?:
maxSize?:
ttlMs?:
RBAC methodsDirect link to RBAC methods
getRoles(user)Direct link to getrolesuser
Returns Google Workspace group role IDs for a user.
const roles = await rbac.getRoles(user)
Returns: Promise<string[]>
getPermissions(user)Direct link to getpermissionsuser
Returns Mastra permissions resolved from Google Workspace groups and roleMapping.
const permissions = await rbac.getPermissions(user)
Returns: Promise<string[]>
hasPermission(user, permission)Direct link to haspermissionuser-permission
Checks whether a user has a permission.
const canReadAgents = await rbac.hasPermission(user, 'agents:read')
Returns: Promise<boolean>
hasRole(user, role)Direct link to 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)Direct link to 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)Direct link to 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()Direct link to getavailableroles
Returns the role IDs configured in roleMapping, excluding _default.
const roles = await rbac.getAvailableRoles()
Returns: Promise<{ id: string; name: string }[]>
getPermissionsForRole(roleId)Direct link to getpermissionsforroleroleid
Returns the permissions configured for a role ID.
const permissions = await rbac.getPermissionsForRole('engineering@example.com')
Returns: Promise<string[]>
clearCache()Direct link to clearcache
Clears all cached Google Workspace group lookups.
rbac.clearCache()
Returns: void
clearUserCache(userKey)Direct link to 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()Direct link to getcachestats
Returns the current group lookup cache size and maximum size.
const stats = rbac.getCacheStats()
Returns: { size: number; maxSize: number }
Additional configurationDirect link to Additional 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 does not 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 does not automatically read service-account environment variables. Pass service-account credentials through the serviceAccount option, or pass accessToken / getAccessToken.