MastraAuthAuth0 Class
The MastraAuthAuth0
class provides authentication for Mastra using Auth0. It verifies incoming requests using Auth0-issued JWT tokens and integrates with the Mastra server using the experimental_auth
option.
Prerequisites
This example uses Auth0 authentication. Make sure to:
- Create an Auth0 account at auth0.comÂ
- Set up an Application in your Auth0 Dashboard
- Configure an API in your Auth0 Dashboard with an identifier (audience)
- Configure your application’s allowed callback URLs, web origins, and logout URLs
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=your-api-identifier
Note: You can find your domain in the Auth0 Dashboard under Applications > Settings. The audience is the identifier of your API configured in Auth0 Dashboard > APIs.
For detailed setup instructions, refer to the Auth0 quickstarts for your specific platform.
Installation
Before you can use the MastraAuthAuth0
class you have to install the @mastra/auth-auth0
package.
npm install @mastra/auth-auth0@latest
Usage examples
Basic usage with environment variables
import { Mastra } from "@mastra/core/mastra";
import { MastraAuthAuth0 } from '@mastra/auth-auth0';
export const mastra = new Mastra({
// ..
server: {
experimental_auth: new MastraAuthAuth0(),
},
});
Custom configuration
import { Mastra } from "@mastra/core/mastra";
import { MastraAuthAuth0 } from '@mastra/auth-auth0';
export const mastra = new Mastra({
// ..
server: {
experimental_auth: new MastraAuthAuth0({
domain: process.env.AUTH0_DOMAIN,
audience: process.env.AUTH0_AUDIENCE
}),
},
});
Configuration
User Authorization
By default, MastraAuthAuth0
allows all authenticated users who have valid Auth0 tokens for the specified audience. The token verification ensures that:
- The token is properly signed by Auth0
- The token is not expired
- The token audience matches your configured audience
- The token issuer matches your Auth0 domain
To customize user authorization, provide a custom authorizeUser
function:
import { MastraAuthAuth0 } from '@mastra/auth-auth0';
const auth0Provider = new MastraAuthAuth0({
authorizeUser: async (user) => {
// Custom authorization logic
return user.email?.endsWith('@yourcompany.com') || false;
}
});
See the MastraAuthAuth0 API reference for all available configuration options.
Client-side setup
When using Auth0 auth, you’ll need to set up the Auth0 React SDK, authenticate users, and retrieve their access tokens to pass to your Mastra requests.
Setting up Auth0 React SDK
First, install and configure the Auth0 React SDK in your application:
npm install @auth0/auth0-react
import React from 'react';
import { Auth0Provider } from '@auth0/auth0-react';
const Auth0ProviderWithHistory = ({ children }) => {
return (
<Auth0Provider
domain={process.env.REACT_APP_AUTH0_DOMAIN}
clientId={process.env.REACT_APP_AUTH0_CLIENT_ID}
authorizationParams={{
redirect_uri: window.location.origin,
audience: process.env.REACT_APP_AUTH0_AUDIENCE,
scope: "read:current_user update:current_user_metadata"
}}
>
{children}
</Auth0Provider>
);
};
export default Auth0ProviderWithHistory;
Retrieving access tokens
Use the Auth0 React SDK to authenticate users and retrieve their access tokens:
import { useAuth0 } from '@auth0/auth0-react';
export const useAuth0Token = () => {
const { getAccessTokenSilently } = useAuth0();
const getAccessToken = async () => {
const token = await getAccessTokenSilently();
return token;
};
return { getAccessToken };
};
Refer to the Auth0 React SDK documentation for more authentication methods and configuration options.
Configuring MastraClient
When experimental_auth
is enabled, all requests made with MastraClient
must include a valid Auth0 access token in the Authorization
header:
import { MastraClient } from "@mastra/client-js";
export const createMastraClient = (accessToken: string) => {
return new MastraClient({
baseUrl: "https://<mastra-api-url>",
headers: {
Authorization: `Bearer ${accessToken}`
}
});
};
Note: The access token must be prefixed with
Bearer
in the Authorization header.
See Mastra Client SDK for more configuration options.
Making authenticated requests
Once MastraClient
is configured with the Auth0 access token, you can send authenticated requests:
import React, { useState } from 'react';
import { useAuth0 } from '@auth0/auth0-react';
import { MastraClient } from '@mastra/client-js';
export const MastraApiTest = () => {
const { getAccessTokenSilently } = useAuth0();
const [result, setResult] = useState(null);
const callMastraApi = async () => {
const token = await getAccessTokenSilently();
const mastra = new MastraClient({
baseUrl: "http://localhost:4111",
headers: {
Authorization: `Bearer ${token}`
}
});
const weatherAgent = mastra.getAgent("weatherAgent");
const response = await weatherAgent.generate({
messages: "What's the weather like in New York"
});
setResult(response.text);
};
return (
<div>
<button onClick={callMastraApi}>
Test Mastra API
</button>
{result && (
<div className="result">
<h6>Result:</h6>
<pre>{result}</pre>
</div>
)}
</div>
);
};