Use AI to integrate Auth0
Use AI to integrate Auth0
If you use an AI coding assistant like Claude Code, Cursor, or GitHub Copilot, you can add Auth0 API authentication automatically in minutes using agent skills.Install:Then ask your AI assistant:Your AI assistant will automatically create your Auth0 API, fetch credentials, install
express-oauth2-jwt-bearer, configure the JWT middleware, and protect your API endpoints with token validation. Full agent skills documentation →Prerequisites: Before you begin, ensure you have the following installed:
- Node.js 18 LTS or newer (supports
^18.12.0 || ^20.2.0 || ^22.1.0 || ^24.0.0) - npm 8+ or yarn 1.22+ or pnpm 8+
node --version && npm --versionExpress Version Compatibility: This quickstart works with Express 4.x and Express 5.x.Get Started
This quickstart demonstrates how to protect Express.js API endpoints using JWT access tokens. You’ll build a secure API that validates Auth0 access tokens, protects routes, and implements scope-based authorization.Create a new project
Create a new directory for your Express API and initialize a Node.js project.Initialize the projectCreate the project structure
Install the express-oauth2-jwt-bearer SDK
Install the required dependenciesUpdate your
package.json to add start scripts:package.json
Setup your Auth0 API
Next, you need to create a new API on your Auth0 tenant and add the environment variables to your project.You have two options to set up your Auth0 API: use a CLI command or configure manually via the Dashboard:
- CLI
- Dashboard
Run the following command in your project’s root directory to create an Auth0 API:After creation, copy the Identifier and your Domain values, then create your
.env file:.env
This command will:
- Check if you’re authenticated (and prompt for login if needed)
- Create an Auth0 API with the specified identifier
- Display the API details including the domain and identifier
Configure the JWT middleware
Create your Express server and configure JWT validation:What this does:
server.js
- Creates JWT validation middleware using your Auth0 domain and API audience
- Validates the
issandaudclaims on incoming access tokens - Makes
checkJwtavailable for protecting individual routes
Create API routes
Add public and protected routes to your Key points:
server.js:server.js
- Public routes don’t require authentication
- Protected routes use the
checkJwtmiddleware to require a valid JWT - Scoped routes use
requiredScopes()to require specific permissions in the token req.auth.payloadcontains the decoded JWT claims for authenticated requests- The
subclaim contains the user’s unique identifier
Run your API
Start the development server:Your API is now running at http://localhost:3001.
The
--watch flag in Node.js 18+ automatically restarts the server when files change.Test your API
Test the public endpoint (no authentication required):You should see:Test the protected endpoint without a token (should fail):You should see a 401 Unauthorized error:To test with a valid token:You should see:
- Go to Auth0 Dashboard → Applications → APIs
- Select your API → Test tab
- Copy the generated access token
CheckpointYou should now have a protected API. Your API:
- Accepts requests to public endpoints without authentication
- Rejects requests to protected endpoints without a valid token
- Validates JWT tokens against your Auth0 domain and audience
- Provides user information from the token claims via
req.auth.payload
Advanced Usage
Scope-Based Authorization
Scope-Based Authorization
Custom Claim Validation
Custom Claim Validation
Beyond scopes, you can validate custom claims in the JWT payload:
server.js
Custom claims must use namespaced URLs (e.g.,
https://myapp.com/roles) unless they’re standard OIDC claims. Learn more about custom claims.Optional Authentication (Mixed Public/Private Routes)
Optional Authentication (Mixed Public/Private Routes)
Allow both authenticated and anonymous access to the same route:
server.js
CORS Configuration
CORS Configuration
Enable CORS to allow requests from web applications:For production, specify exact origins:
server.js
server.js
Custom Error Handling
Custom Error Handling
Add comprehensive error handling for authentication errors:
server.js
TypeScript Support
TypeScript Support
For TypeScript projects, install type definitions and configure your project:Create Add a Run with:
server.ts:server.ts
tsconfig.json:tsconfig.json
npx ts-node server.tsTroubleshooting
Common Issues and Solutions
Common Issues and Solutions
”No authorization token was found”
Problem: The API cannot find the access token in the request.Solutions:- Ensure the
Authorizationheader is present:Authorization: Bearer YOUR_TOKEN - Check that “Bearer” is included before the token
- Verify the token is not expired
”Invalid token” or “jwt malformed”
Problem: The token format is invalid.Solutions:- Ensure you’re using an access token, not an ID token
- The token should be obtained with your API’s
audienceparameter - Check that the token is a valid JWT (should have three parts separated by dots)
Unexpected “iss” or “aud” value
Problem: The issuer or audience in the token doesn’t match your configuration.Solutions:- Decode your token at jwt.io
- Check the
issclaim matcheshttps://YOUR_AUTH0_DOMAIN/(note the trailing slash) - Check the
audclaim matches yourAUTH0_AUDIENCEexactly - Verify your
.envvalues:
“You must provide an issuerBaseURL” or “audience is required”
Problem: Environment variables are not being loaded.Solutions:- Ensure
.envfile exists in your project root - Verify
dotenvis installed:npm install dotenv - Add
require('dotenv').config()at the very top of your server file - Check variable names match exactly (case-sensitive)
401 Unauthorized on all requests
Possible causes:- Token is expired
- Audience doesn’t match
- Issuer doesn’t match
- Decode your token at jwt.io
- Check the
expclaim hasn’t passed - Verify
audclaim matches yourAUTH0_AUDIENCEexactly - Verify
issclaim ishttps://{AUTH0_DOMAIN}/ - Ensure Authorization header format is
Bearer YOUR_TOKEN(with space)
403 Forbidden with “insufficient_scope”
Problem: The token doesn’t have the required scopes.Solutions:- Verify the scopes are defined in your Auth0 API (Dashboard → Applications → APIs → Permissions)
- Request the scopes when obtaining the token
- Check the token’s
scopeclaim includes the required scopes
CORS errors in browser
Problem: Browser blocks API requests due to CORS policy.Solution: Install and configurecors:Next Steps
Now that you have a protected API, consider exploring:- Role-Based Access Control - Implement fine-grained permissions
- API Authorization Best Practices - Learn about access token best practices
- Monitor Your API - Set up logging and monitoring
- Auth0 Community - Get help from the community
Resources
- express-oauth2-jwt-bearer GitHub - Source code and examples
- Express.js Documentation - Learn more about Express
- Auth0 API Authentication - Understanding access tokens
- JWT.io - Debug and decode JWTs