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
go-jwt-middleware, configure the validator, and protect your API endpoints with JWT validation. Full agent skills documentation →Get Started
You’ll build a Go API with three endpoints demonstrating different protection levels: public access, JWT-authenticated, and permission-scoped. The complete implementation uses go-jwt-middleware v3 with Go’s standardnet/http library.
View Sample on GitHub
Complete working example with tests
Create a new project
Create a new directory for your Go API and initialize a module.Install the required dependencies:Create the project structure:
View expected go.mod
View expected go.mod
go.mod
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: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
Define API permissions
Permissions (scopes) let you define how resources can be accessed. For example, grant
read access to managers and write access to administrators.- In your API settings, click the Permissions tab
- Create the following permission:
| Permission | Description |
|---|---|
read:messages | Read messages from the API |
This tutorial uses the
read:messages scope to protect the scoped endpoint. You can define additional permissions based on your application’s needs.Create configuration loader
Create a config package to load and validate environment variables.What this does:
internal/config/auth.go
- Loads Auth0 domain and audience from environment variables
- Validates that required configuration is present at startup
- Returns a type-safe config struct for use across the application
Create custom claims and JWT validator
Custom claims allow you to extract and validate application-specific data from JWTs. The validator is the core component that verifies tokens against Auth0.Key points:
- claims.go
- validator.go
internal/auth/claims.go
- The
Validatemethod is called automatically by the middleware after parsing the JWT HasScopeparses space-separated scopes for permission-based access control- The validator uses JWKS caching (5 min TTL) and allows 30s clock skew
- RS256 algorithm is explicitly set to prevent algorithm confusion attacks
Create HTTP middleware and handlers
The middleware wraps the validator for HTTP requests. The handlers demonstrate three protection levels: public, private, and permission-scoped.Protection levels:
- middleware.go
- api.go
internal/auth/middleware.go
- Public (
/api/public) — No authentication required - Private (
/api/private) — Valid JWT required - Scoped (
/api/private-scoped) — Valid JWT +read:messagespermission required
Create the main server
Wire everything together in the main entry point with production-ready timeouts and graceful shutdown:
cmd/server/main.go
Project structure
Project structure
Run and test your API
Start the development server:You should see: You should see:Test the private endpoint without a token (should fail):You should see a 401 Unauthorized error:To test with a valid token, navigate to your API in the Auth0 Dashboard, click the Test tab, and copy the access token. Then run:Test the scoped endpoint (requires
Server starting on :8080Test the public endpoint (no authentication required):read:messages permission):CheckpointYou should now have a protected Go 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
- Enforces permission-based access control using scopes
Calling Your API
You can call your protected API from any application by passing an access token in theAuthorization header as a Bearer token.
Client code examples
Client code examples
Obtaining an access token
Obtaining an access token
- Single-Page or Mobile Apps
- Machine-to-Machine (M2M)
If you are calling the API from a Single-Page Application or a Mobile/Native application, after the authorization flow is completed, you will get an access token. How you get the token and how you make the call to the API will depend on the type of application you are developing and the framework you are using.
Single-Page Applications
React, Vue, Angular quickstarts with examples
Mobile / Native Applications
iOS, Android, React Native quickstarts
Advanced Usage
DPoP (Proof-of-Possession) Security
DPoP (Proof-of-Possession) Security
DPoP (Demonstrating Proof-of-Possession) per RFC 9449 provides enhanced security by preventing token theft through cryptographic key binding.DPoP Modes:
internal/auth/middleware.go
DPoPAllowed(default) — Accept both Bearer and DPoP tokensDPoPRequired— Only accept DPoP tokens, reject BearerDPoPDisabled— Only accept Bearer tokens, reject DPoP
DPoP is recommended for financial APIs, healthcare APIs, and high-security enterprise applications. Learn more in the DPoP documentation.
CORS Configuration
CORS Configuration
Enable CORS to allow requests from web applications. You can use a simple middleware or a library like rs/cors:For production, specify exact origins instead of wildcards.
cmd/server/main.go
Structured Logging with slog
Structured Logging with slog
Enable detailed logging for debugging token validation:Add startup verification:
internal/auth/middleware.go
cmd/server/main.go
Troubleshooting
Common Issues and Solutions
Common Issues and Solutions
”Failed to validate JWT” or 401 Unauthorized
Problem: The API cannot find or validate the access token.Solutions:- Ensure the
Authorizationheader is present:Authorization: Bearer YOUR_TOKEN - Check that “Bearer” is included before the token
- Verify the token is not expired
- Ensure you’re using an access token, not an ID token
”aud claim mismatch”
Problem: The token’s audience doesn’t match your API.Solution: VerifyAUTH0_AUDIENCE exactly matches your API Identifier from the Auth0 Dashboard. The audience should NOT have a trailing slash:”unexpected signing method”
Problem: Token algorithm doesn’t match validator configuration.Solutions:- Auth0 uses RS256 by default (asymmetric)
- Ensure your validator specifies
validator.RS256 - Never use
validator.HS256for Auth0 tokens unless specifically configured
JWKS endpoint unreachable
Problem: The JWKS caching provider cannot reach Auth0’s public key endpoint.Solutions:- Check network connectivity to Auth0 (firewall/proxy settings)
- Test JWKS endpoint manually:
curl https://YOUR_AUTH0_DOMAIN/.well-known/jwks.json - Verify correct Auth0 region (us/eu/au)
Wrong import path
Problem:cannot find package "github.com/auth0/go-jwt-middleware/v3/..."Solution: Ensure all imports use the /v3 suffix:Clock skew / token expired errors
Problem: Server clock is out of sync, causing valid tokens to appear expired.Solution: The validator already includes 30s clock skew tolerance. If you need more, adjust:Claims extraction fails
Problem:Failed to retrieve claims when using generics.Solution: Ensure you’re using the correct type parameter:Next Steps
Now that you have a protected API, consider exploring:- Role-Based Access Control — Implement fine-grained permissions
- Access Token Best Practices — Learn about token security
- Monitor Your API — Set up logging and monitoring
- Production Checklist — Pre-launch security review
Resources
- go-jwt-middleware GitHub — Source code, examples, and DPoP support
- Go API Sample — Complete working example
- Auth0 Community — Get help from the community