diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 78a8448ed4..469518cadf 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -9,12 +9,15 @@ scripts @auth0/project-docs-management-codeowner **/package-lock.json @auth0/project-docs-management-codeowner **/CLAUDE.md @auth0/project-docs-management-codeowner -# Docs Management ownership for generated API references +# Docs Management ownership for generated API & Schema references main/docs/api.mdx @auth0/project-docs-management-codeowner main/docs/api @auth0/project-docs-management-codeowner main/docs/fr-ca/api @auth0/project-docs-management-codeowner main/docs/ja-jp/api @auth0/project-docs-management-codeowner main/docs/oas @auth0/project-docs-management-codeowner +main/docs/events @auth0/project-docs-management-codeowner +main/docs/fr-ca/events @auth0/project-docs-management-codeowner +main/docs/ja-jp/events @auth0/project-docs-management-codeowner # Shared ownership for shared config files .github @auth0/project-docs-writers-codeowner @auth0/project-docs-management-codeowner diff --git a/.github/workflows/sync-agent-skills.yml b/.github/workflows/sync-agent-skills.yml new file mode 100644 index 0000000000..b1693fa497 --- /dev/null +++ b/.github/workflows/sync-agent-skills.yml @@ -0,0 +1,71 @@ +name: Sync agent skills + +on: + schedule: + - cron: '23 9 * * 1' # Weekly Monday 9:23 UTC + workflow_dispatch: + +jobs: + sync-skills: + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + + steps: + - name: Checkout docs-v2 + uses: actions/checkout@v4 + + - name: Fetch latest skills from agent-skills + run: | + SKILLS_DIR="main/.mintlify/skills" + REPO_URL="https://github.com/auth0/agent-skills.git" + TEMP_DIR=$(mktemp -d) + + git clone --depth 1 --sparse "$REPO_URL" "$TEMP_DIR" + cd "$TEMP_DIR" + git sparse-checkout set plugins/*/skills/*/SKILL.md + cd - + + rm -rf "$SKILLS_DIR" + mkdir -p "$SKILLS_DIR" + + for skill_file in "$TEMP_DIR"/plugins/*/skills/*/SKILL.md; do + skill_name=$(basename "$(dirname "$skill_file")") + mkdir -p "$SKILLS_DIR/$skill_name" + cp "$skill_file" "$SKILLS_DIR/$skill_name/SKILL.md" + echo "Synced: $skill_name" + done + + rm -rf "$TEMP_DIR" + echo "--- Skills synced ---" + ls "$SKILLS_DIR" + + - name: Create PR if skills changed + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + git add main/.mintlify/skills/ + if git diff --cached --quiet; then + echo "Skills are up to date — nothing to do" + exit 0 + fi + + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + + BRANCH="chore/sync-agent-skills-$(date +%Y%m%d)" + git checkout -b "$BRANCH" + git commit -m "chore: sync agent skills from auth0/agent-skills" + git push origin "$BRANCH" + + gh pr create \ + --title "chore: sync agent skills" \ + --body "Automated weekly sync of SKILL.md files from [auth0/agent-skills](https://github.com/auth0/agent-skills). + + These files are served via Mintlify's skills discovery endpoint at \`auth0.com/docs/.well-known/skills/\`. + + --- + Auto-generated by [sync-agent-skills](https://github.com/auth0/docs-v2/blob/main/.github/workflows/sync-agent-skills.yml). Approve to deploy." \ + --head "$BRANCH" \ + --base main diff --git a/CLAUDE.md b/CLAUDE.md index 10c27f65c3..984e0f838e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,6 +9,7 @@ This is a **Mintlify-based documentation monorepo** for Auth0. It contains multi - **`main/`** - Primary Auth0 documentation (https://auth0.com/docs) - **`auth4genai/`** - Auth0 for AI Agents documentation (https://auth0.com/ai/docs) - **`ui/`** - Shared React/Vite component library used across documentation sites +- **`universal-components/`** - Shared React/Vite component library used for interactive components documentations Each documentation site (`main`, `auth4genai`) operates independently with its own `docs.json` Mintlify configuration file. @@ -81,7 +82,7 @@ This is **not a managed monorepo** (no Lerna, pnpm workspaces, etc.). Each folde **Content Structure:** - `.mdx` and `.md` files for documentation pages -- YAML frontmatter for metadata (title, description, og/twitter tags) +- YAML frontmatter for metadata (title, description) - `docs.json` defines navigation structure and Mintlify configuration **Reusable Components:** diff --git a/README.md b/README.md index 4a16e0255d..214602256f 100644 --- a/README.md +++ b/README.md @@ -10,4 +10,6 @@ This repo contains the content, configuration, and styling for much of Auth0's d * The `ui` directory contains a shared React component library for both docs sites. (See [the Docs UI library README](./ui/README.md) for more information.) +* The `universal-components` directory contains a shared React universal component library for both docs sites. (See [the Docs UI library README](./universal-components/README.md) for more information.) + To contribute to the docs, please coordinate with the Auth0 Product Docs and/or Product Management team, then read our [contribution guide](./CONTRIBUTING.md). diff --git a/main/.mintignore b/main/.mintignore new file mode 100644 index 0000000000..10a438adde --- /dev/null +++ b/main/.mintignore @@ -0,0 +1 @@ +_metadata.json diff --git a/main/.mintlify/skills/auth0-android/SKILL.md b/main/.mintlify/skills/auth0-android/SKILL.md new file mode 100644 index 0000000000..0048023133 --- /dev/null +++ b/main/.mintlify/skills/auth0-android/SKILL.md @@ -0,0 +1,183 @@ +--- +name: auth0-android +description: Use when adding authentication to Android applications (Kotlin/Java) with Web Auth, biometric-protected credentials, and MFA - integrates com.auth0.android:auth0 SDK for native Android apps +license: Proprietary +metadata: + author: Auth0 +--- + +# Auth0 Android Integration + +Add authentication to Android applications using `com.auth0.android:auth0`. + +> **Agent instruction:** Before providing SDK setup instructions, fetch the latest release version by running: +> ``` +> gh api repos/auth0/Auth0.Android/releases/latest --jq '.tag_name' +> ``` +> Use the returned version in all `implementation` dependency lines instead of any hardcoded version below. If the command fails, fall back to checking https://github.com/auth0/Auth0.Android/releases. + +## Prerequisites + +- Android API 21 or higher +- Kotlin or Java project +- Auth0 account with a Native application configured +- If you don't have Auth0 set up, see [auth0-quickstart](/auth0-quickstart) + +## When NOT to Use + +- **React Native apps**: Use [auth0-react-native](/auth0-react-native) +- **Flutter apps**: Use the native Flutter Auth0 SDK +- **Web SPAs** (React, Angular, Vue): Use [auth0-react](/auth0-react), [auth0-angular](/auth0-angular), or [auth0-vue](/auth0-vue) +- **Node.js/Express servers**: Use [auth0-express](/auth0-express) +- **iOS/macOS apps**: Use [auth0-swift](/auth0-swift) + +## Quick Start Workflow + +1. **Install SDK**: Add the Auth0 Android SDK dependency to your `build.gradle`: + ```gradle + implementation 'com.auth0.android:auth0:{LATEST_VERSION}' + ``` + +2. **Configure Auth0**: + + See [**Setup Guide**](references/setup.md) for automatic/manual setup, post-setup required project changes, and callback URL configuration. + +3. **Initialize**: Create an Auth0 account instance: + ```kotlin + import com.auth0.android.Auth0 + + val account = Auth0.getInstance(context) + ``` + +4. **Add Auth UI**: Implement login and logout with Web Auth: + + > **Agent instruction:** Before adding new UI elements, search the project for existing click handlers for login, logout, sign-in, or sign-out buttons (e.g., `loginButton`, `signInButton`, `logoutButton`, `signOutButton`, or `setOnClickListener` with auth-related naming). If existing handlers are found, hook the Auth0 code into them without modifying the existing UI. Only create new buttons if no existing handlers are found. + + **Login:** + ```kotlin + import com.auth0.android.Auth0 + import com.auth0.android.authentication.AuthenticationAPIClient + import com.auth0.android.authentication.storage.SecureCredentialsManager + import com.auth0.android.authentication.storage.SharedPreferencesStorage + import com.auth0.android.callback.Callback + import com.auth0.android.authentication.AuthenticationException + import com.auth0.android.provider.WebAuthProvider + import com.auth0.android.result.Credentials + + val account = Auth0.getInstance(context) + val authentication = AuthenticationAPIClient(account) + val storage = SharedPreferencesStorage(context) + val credentialsManager = SecureCredentialsManager(context, authentication, storage) + + WebAuthProvider.login(account) + .withScheme(getString(R.string.com_auth0_scheme)) + .withScope("openid profile email offline_access") + .start(this, object : Callback { + override fun onSuccess(result: Credentials) { + // User authenticated + val idToken = result.idToken + val accessToken = result.accessToken + // Store credentials securely + credentialsManager.saveCredentials(result) + } + override fun onFailure(error: AuthenticationException) { + // Handle authentication failure + Log.e("Auth0", "Authentication failed", error) + } + }) + ``` + + **Logout:** + ```kotlin + WebAuthProvider.logout(account) + .withScheme(getString(R.string.com_auth0_scheme)) + .start(this, object : Callback { + override fun onSuccess(result: Void) { + // User logged out + } + override fun onFailure(error: AuthenticationException) { + Log.e("Auth0", "Logout failed", error) + } + }) + ``` + +5. **Build & Verify**: + + > **Agent instruction:** After completing the integration, build the project to verify it compiles successfully: + > ```bash + > ./gradlew assembleDebug + > ``` + > If the build fails, analyze the error output and fix the issues. Common integration build failures include: + > - **Unresolved reference**: Missing import statements — add the required `import com.auth0.android.*` imports + > - **Cannot resolve symbol `R.string.com_auth0_scheme`**: `strings.xml` not updated — verify `com_auth0_scheme`, `com_auth0_client_id`, and `com_auth0_domain` entries exist + > - **Incompatible types in callback**: Callback type parameters don't match — ensure `Callback` for login and `Callback` for logout + > - **Unresolved `lifecycleScope`**: Missing dependency — add `implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.6.+'` or move code out of coroutine scope + > - **minSdk too low**: SDK requires API 21+ — update `minSdkVersion` to at least 21 + > - **Java version mismatch**: SDK requires Java 8 — add `compileOptions` with `JavaVersion.VERSION_1_8` + > + > Re-run the build after each fix. Track the number of build-fix iterations. + > + > **Failcheck:** If the build still fails after 5–6 fix attempts, stop and ask the user using `AskUserQuestion`: + > _"The build is still failing after several fix attempts. How would you like to proceed?"_ + > - **Let the skill continue fixing iteratively** — continue the build-fix loop for another 5–6 attempts + > - **Fix it manually** — show the remaining errors and let the user resolve them + > - **Skip build verification** — proceed without a successful build + > + > Repeat this check after every 5–6 iterations if errors persist. Do not leave the project in a non-compiling state without the user's explicit consent. + + The callback URL must match your Auth0 application settings: `{SCHEME}://{YOUR_AUTH0_DOMAIN}/android/{YOUR_APP_PACKAGE_NAME}/callback` + +## Detailed Documentation + +- [**Setup Guide**](references/setup.md) — Install SDK, configure Auth0 application, set up callback URLs, Android App Links, custom schemes, ProGuard/R8 +- [**Integration Patterns**](references/integration.md) — Web Auth login/logout, credential storage, biometric authentication, database login, passwordless authentication, MFA handling, custom tabs, error handling +- [**Testing & Reference**](references/api.md) — Testing checklist, common issues, security considerations, API reference + +## Common Mistakes + +| Mistake | Fix | +|---------|-----| +| App type not set to Native in Auth0 Dashboard | Create a Native application type in your Auth0 tenant. The Android SDK requires Native app configuration, not Machine-to-Machine or other types. | +| Missing callback URL in Allowed Callback URLs | Add `{SCHEME}://{YOUR_AUTH0_DOMAIN}/android/{YOUR_APP_PACKAGE_NAME}/callback` to your Auth0 application's Allowed Callback URLs setting, where `{SCHEME}` matches `com_auth0_scheme` in `strings.xml` (e.g., `demo` by default). | +| Missing `` | Add the INTERNET permission to `AndroidManifest.xml`. The SDK requires network access for authentication. | +| Custom scheme in lowercase | Android requires scheme names to be lowercase. Use `https` (recommended) or lowercase custom scheme like `myapp://callback`. | +| Forgetting `.validateClaims()` on direct auth calls | Always call `.validateClaims()` when using `AuthenticationAPIClient` directly (for database, passwordless, or API login). Web Auth validates automatically. | +| Storing tokens in SharedPreferences without encryption | Use `SecureCredentialsManager` to store credentials. Never store tokens manually in plain text. The manager encrypts tokens at rest. | +| Missing manifest placeholders | Add `manifestPlaceholders = [auth0Domain: "@string/com_auth0_domain", auth0Scheme: "@string/com_auth0_scheme"]` to your `build.gradle` `defaultConfig` block. | + +## Related Skills + +- [auth0-quickstart](/auth0-quickstart) — Set up an Auth0 account and application +- [auth0-mfa](/auth0-mfa) — Configure multi-factor authentication +- [auth0-swift](/auth0-swift) — iOS/macOS authentication + +## Quick Reference + +### Core Classes + +| Class | Purpose | +|-------|---------| +| `Auth0` | Entry point for SDK, holds app credentials | +| `WebAuthProvider` | OAuth 2.0 login/logout via browser | +| `AuthenticationAPIClient` | Direct API calls (database login, passwordless, MFA) | +| `SecureCredentialsManager` | Secure storage and retrieval of credentials | +| `Credentials` | User tokens and expiration | + +### Common Use Cases + +- [Log in with Web Auth](references/integration.md#web-auth-login) +- [Log out](references/integration.md#web-auth-logout) +- [Store credentials securely](references/integration.md#credential-storage) +- [Require biometric authentication](references/integration.md#biometric-protected-credentials) +- [Database login](references/integration.md#database-login) +- [Passwordless authentication](references/integration.md#passwordless-authentication) +- [Handle MFA](references/integration.md#mfa-handling) +- [Call protected APIs](references/integration.md#calling-protected-apis) + +## References + +- [Auth0 Android SDK Documentation](https://auth0.com/docs/libraries/auth0-android) +- [Auth0 Android GitHub Repository](https://github.com/auth0/auth0-android) +- [Android SDK Javadoc](https://auth0.com/docs/references/android) +- [Auth0 Android Quickstart](https://auth0.com/docs/quickstart/native/android) +- [Sample App](https://github.com/auth0-samples/auth0-android-sample) diff --git a/main/.mintlify/skills/auth0-angular/SKILL.md b/main/.mintlify/skills/auth0-angular/SKILL.md new file mode 100644 index 0000000000..6d71fcdea1 --- /dev/null +++ b/main/.mintlify/skills/auth0-angular/SKILL.md @@ -0,0 +1,204 @@ +--- +name: auth0-angular +description: Use when adding authentication to Angular applications with route guards and HTTP interceptors - integrates @auth0/auth0-angular SDK for SPAs +license: Apache-2.0 +metadata: + author: Auth0 +--- + +# Auth0 Angular Integration + +Add authentication to Angular applications using @auth0/auth0-angular. + +--- + +## Prerequisites + +- Angular 13+ application +- Auth0 account and application configured +- If you don't have Auth0 set up yet, use the `auth0-quickstart` skill first + +## When NOT to Use + +- **AngularJS (1.x)** - This SDK requires Angular 13+, use legacy solutions for AngularJS +- **Mobile applications** - Use `auth0-react-native` for React Native or native SDKs for Ionic +- **Backend APIs** - Use JWT validation middleware for your server language + +--- + +## Quick Start Workflow + +### 1. Install SDK + +```bash +npm install @auth0/auth0-angular +``` + +### 2. Configure Environment + +**For automated setup with Auth0 CLI**, see [Setup Guide](references/setup.md) for complete scripts. + +**For manual setup:** + +Update `src/environments/environment.ts`: + +```typescript +export const environment = { + production: false, + auth0: { + domain: 'your-tenant.auth0.com', + clientId: 'your-client-id', + authorizationParams: { + redirect_uri: window.location.origin + } + } +}; +``` + +### 3. Configure Auth Module + +**For standalone components (Angular 14+):** + +Update `src/app/app.config.ts`: + +```typescript +import { ApplicationConfig } from '@angular/core'; +import { provideAuth0 } from '@auth0/auth0-angular'; +import { environment } from '../environments/environment'; + +export const appConfig: ApplicationConfig = { + providers: [ + provideAuth0({ + domain: environment.auth0.domain, + clientId: environment.auth0.clientId, + authorizationParams: environment.auth0.authorizationParams + }) + ] +}; +``` + +**For NgModule-based apps:** + +Update `src/app/app.module.ts`: + +```typescript +import { AuthModule } from '@auth0/auth0-angular'; +import { environment } from '../environments/environment'; + +@NgModule({ + imports: [ + AuthModule.forRoot({ + domain: environment.auth0.domain, + clientId: environment.auth0.clientId, + authorizationParams: environment.auth0.authorizationParams + }) + ] +}) +export class AppModule {} +``` + +### 4. Add Authentication UI + +Update `src/app/app.component.ts`: + +```typescript +import { Component } from '@angular/core'; +import { AuthService } from '@auth0/auth0-angular'; + +@Component({ + selector: 'app-root', + template: ` +
+

Loading...

+
+ + + +
+ +

Welcome, {{ user.name }}!

+ +
+
+ + + + +
+ ` +}) +export class AppComponent { + constructor(public auth: AuthService) {} + + login(): void { + this.auth.loginWithRedirect(); + } + + logout(): void { + this.auth.logout({ logoutParams: { returnTo: window.location.origin } }); + } +} +``` + +### 5. Test Authentication + +Start your dev server and test the login flow: + +```bash +ng serve +``` + +--- + +## Detailed Documentation + +- **[Setup Guide](references/setup.md)** - Automated setup scripts (Bash/PowerShell), CLI commands, manual configuration +- **[Integration Guide](references/integration.md)** - Protected routes with guards, HTTP interceptors, error handling +- **[API Reference](references/api.md)** - Complete SDK API, configuration options, services reference, testing strategies + +--- + +## Common Mistakes + +| Mistake | Fix | +|---------|-----| +| Forgot to add redirect URI in Auth0 Dashboard | Add your application URL (e.g., `http://localhost:4200`, `https://app.example.com`) to Allowed Callback URLs in Auth0 Dashboard | +| Not configuring AuthModule properly | Must call `AuthModule.forRoot()` in NgModule or `provideAuth0()` in standalone config | +| Accessing auth before initialization | Use `isLoading$` observable to wait for SDK initialization | +| Storing tokens manually | Never manually store tokens - SDK handles secure storage automatically | +| Missing HTTP interceptor | Use `authHttpInterceptorFn` or `AuthHttpInterceptor` to attach tokens to API calls | +| Route guard not protecting routes | Apply `AuthGuard` (or `authGuardFn`) to protected routes in routing config | + +--- + +## Related Skills + +- `auth0-quickstart` - Basic Auth0 setup +- `auth0-migration` - Migrate from another auth provider +- `auth0-mfa` - Add Multi-Factor Authentication + +--- + +## Quick Reference + +**Core Services:** +- `AuthService` - Main authentication service +- `isAuthenticated$` - Observable check if user is logged in +- `user$` - Observable user profile information +- `loginWithRedirect()` - Initiate login +- `logout()` - Log out user +- `getAccessTokenSilently()` - Get access token for API calls + +**Common Use Cases:** +- Login/Logout buttons → See Step 4 above +- Protected routes with guards → [Integration Guide](references/integration.md#protected-routes) +- HTTP interceptors for API calls → [Integration Guide](references/integration.md#http-interceptor) +- Error handling → [Integration Guide](references/integration.md#error-handling) + +--- + +## References + +- [Auth0 Angular SDK Documentation](https://auth0.com/docs/libraries/auth0-angular) +- [Auth0 Angular Quickstart](https://auth0.com/docs/quickstart/spa/angular) +- [SDK GitHub Repository](https://github.com/auth0/auth0-angular) diff --git a/main/.mintlify/skills/auth0-aspnetcore-api/SKILL.md b/main/.mintlify/skills/auth0-aspnetcore-api/SKILL.md new file mode 100644 index 0000000000..3a84b49086 --- /dev/null +++ b/main/.mintlify/skills/auth0-aspnetcore-api/SKILL.md @@ -0,0 +1,230 @@ +--- +name: auth0-aspnetcore-api +description: "Use when securing ASP.NET Core Web API endpoints with JWT Bearer token validation, scope/permission checks, or stateless auth - integrates Auth0.AspNetCore.Authentication.Api for REST APIs receiving access tokens from frontends or mobile apps. Also handles DPoP proof-of-possession token binding. Triggers on: AddAuth0ApiAuthentication, .NET Web API auth, JWT validation, UseAuthentication, UseAuthorization." +license: Apache-2.0 +metadata: + author: Auth0 +--- + +# Auth0 ASP.NET Core Web API Integration + +Protect ASP.NET Core Web API endpoints with JWT access token validation using Auth0.AspNetCore.Authentication.Api. + +--- + +## Prerequisites + +- .NET 8.0 SDK or higher +- Auth0 API configured (not Application - must be API resource) +- If you don't have Auth0 set up yet, use the `auth0-quickstart` skill first + +## When NOT to Use + +- **Server-rendered web applications** - Use session-based auth (Auth0.AspNetCore.Authentication) for MVC/Razor Pages apps +- **Single Page Applications** - Use `auth0-react`, `auth0-vue`, or `auth0-angular` for client-side auth +- **Mobile applications** - Use `auth0-react-native` for React Native/Expo +- **Blazor WebAssembly** - Requires different auth approach (OIDC client-side) + +--- + +## Quick Start Workflow + +### 1. Install SDK + +```bash +dotnet add package Auth0.AspNetCore.Authentication.Api +``` + +### 2. Create Auth0 API + +You need an **API** (not Application) in Auth0. + +> **STOP — ask the user before proceeding.** +> +> Ask exactly this question and wait for their answer before doing anything else: +> +> > "How would you like to create the Auth0 API resource? +> > 1. **Automated** — I'll run Auth0 CLI scripts that create the resource and write the exact values to your appsettings.json automatically. +> > 2. **Manual** — You create the API yourself in the Auth0 Dashboard (or via `auth0 apis create`) and provide me the Domain and Audience. +> > +> > Which do you prefer? (1 = Automated / 2 = Manual)" +> +> Do NOT proceed to any setup steps until the user has answered. Do NOT default to manual. + +**If the user chose Automated**, follow the [Setup Guide](references/setup.md) for complete CLI scripts. The automated path writes `appsettings.json` for you — skip Step 3 below and proceed directly to Step 4. + +**If the user chose Manual**, follow the [Setup Guide](references/setup.md) (Manual Setup section) for full instructions including User Secrets and environment variable options. Then continue with Step 3 below. + +Quick reference for manual API creation: + +```bash +# Using Auth0 CLI +auth0 apis create \ + --name "My ASP.NET Core API" \ + --identifier https://my-api.example.com +``` + +Or create manually in Auth0 Dashboard → Applications → APIs + +### 3. Configure appsettings.json + +```json +{ + "Auth0": { + "Domain": "your-tenant.auth0.com", + "Audience": "https://my-api.example.com" + } +} +``` + +**Important:** Domain must NOT include `https://`. The library constructs the authority URL automatically. + +### 4. Configure Program.cs + +```csharp +var builder = WebApplication.CreateBuilder(args); + +// Register Auth0 JWT validation +builder.Services.AddAuth0ApiAuthentication(options => +{ + options.Domain = builder.Configuration["Auth0:Domain"]; + options.JwtBearerOptions = new JwtBearerOptions + { + Audience = builder.Configuration["Auth0:Audience"] + }; +}); + +builder.Services.AddAuthorization(); + +var app = builder.Build(); + +// Middleware order matters: authentication before authorization +app.UseAuthentication(); +app.UseAuthorization(); + +// Add your endpoints here (see Step 5) +app.MapGet("/api/public", () => Results.Ok(new { message = "Public" })); + +app.Run(); +``` + +### 5. Protect Endpoints + +**Minimal API:** + +```csharp +// Public endpoint - no authentication +app.MapGet("/api/public", () => Results.Ok(new { message = "Hello from a public endpoint!" })); + +// Protected endpoint - requires valid JWT +app.MapGet("/api/private", (HttpContext ctx) => +{ + var userId = ctx.User.FindFirst("sub")?.Value; + return Results.Ok(new { message = "Hello from a protected endpoint!", userId }); +}).RequireAuthorization(); +``` + +**Controller-based:** + +```csharp +[ApiController] +[Route("api")] +public class MessagesController : ControllerBase +{ + [HttpGet("public")] + public IActionResult Public() => + Ok(new { message = "Hello from a public endpoint!" }); + + [Authorize] + [HttpGet("private")] + public IActionResult Private() => + Ok(new { message = "Hello from a protected endpoint!", userId = User.FindFirst("sub")?.Value }); +} +``` + +### 6. Test API + +Test public endpoint: + +```bash +curl http://localhost:5000/api/public +``` + +Test protected endpoint (requires access token): + +```bash +curl http://localhost:5000/api/private \ + -H "Authorization: Bearer YOUR_ACCESS_TOKEN" +``` + +Get a test token via Client Credentials flow or Auth0 Dashboard → APIs → Test tab. + +--- + +## Common Mistakes + +| Mistake | Fix | +|---------|-----| +| Domain includes `https://` | Use `your-tenant.auth0.com` format only - no scheme prefix | +| Audience doesn't match API Identifier | Must exactly match the API Identifier set in Auth0 Dashboard | +| Created Application instead of API in Auth0 | Must create API resource in Auth0 Dashboard → Applications → APIs | +| Wrong middleware order | `UseAuthentication()` must come before `UseAuthorization()` | +| Using ID token instead of access token | Must use **access token** for API auth, not ID token | +| HTTPS certificate errors locally | Run `dotnet dev-certs https --trust` | + +--- + +## Scope-Based Authorization + +See [Integration Guide](references/integration.md#scope-based-authorization) for defining and enforcing scope policies. + +--- + +## DPoP Support + +Built-in proof-of-possession token binding per RFC 9449. See [Integration Guide](references/integration.md#dpop-support) for configuration. + +--- + +## Related Skills + +- `auth0-quickstart` - Basic Auth0 setup +- `auth0-mfa` - Add Multi-Factor Authentication + +--- + +## Quick Reference + +**Configuration Options:** +- `options.Domain` - Auth0 tenant domain, no `https://` prefix (required) +- `options.JwtBearerOptions.Audience` - API Identifier from Auth0 API settings (required) +- `options.JwtBearerOptions` - Full access to underlying Microsoft JWT Bearer options + +**User Claims:** +- `ctx.User.FindFirst("sub")?.Value` - User ID (subject) +- `ctx.User.FindFirst("scope")?.Value` - Space-separated scopes +- `ctx.User.FindAll("scope")` - All scope claims + +**Common Use Cases:** +- Protect Minimal API routes → `.RequireAuthorization()` (see Step 5) +- Protect controller actions → `[Authorize]` attribute (see Step 5) +- Scope enforcement → [Integration Guide](references/integration.md#scope-based-authorization) +- DPoP token binding → [Integration Guide](references/integration.md#dpop-support) +- Advanced JWT Bearer config → [API Reference](references/api.md) + +--- + +## Detailed Documentation + +- **[Setup Guide](references/setup.md)** - Auth0 CLI setup, environment configuration +- **[Integration Guide](references/integration.md)** - Scope policies, DPoP, controller patterns, error handling +- **[API Reference](references/api.md)** - Complete configuration options and extension methods + +--- + +## References + +- [Auth0 ASP.NET Core Web API Quickstart](https://auth0.com/docs/quickstart/backend/aspnet-core-webapi) +- [SDK GitHub Repository](https://github.com/auth0/aspnetcore-api) +- [API Documentation](https://auth0.github.io/aspnetcore-api) +- [Access Tokens Guide](https://auth0.com/docs/secure/tokens/access-tokens) diff --git a/main/.mintlify/skills/auth0-express/SKILL.md b/main/.mintlify/skills/auth0-express/SKILL.md new file mode 100644 index 0000000000..a8dfdcf088 --- /dev/null +++ b/main/.mintlify/skills/auth0-express/SKILL.md @@ -0,0 +1,193 @@ +--- +name: auth0-express +description: Use when adding authentication (login, logout, protected routes) to Express.js web applications - integrates express-openid-connect for session-based auth. +license: Apache-2.0 +metadata: + author: Auth0 +--- + +# Auth0 Express Integration + +Add authentication to Express.js web applications using express-openid-connect. + +--- + +## Prerequisites + +- Express.js application +- Auth0 account and application configured +- If you don't have Auth0 set up yet, use the `auth0-quickstart` skill first + +## When NOT to Use + +- **Single Page Applications** - Use `auth0-react`, `auth0-vue`, or `auth0-angular` for client-side auth +- **Next.js applications** - Use `auth0-nextjs` skill which handles both client and server +- **Mobile applications** - Use `auth0-react-native` for React Native/Expo +- **Stateless APIs** - Use JWT validation middleware instead of session-based auth +- **Microservices** - Use JWT validation for service-to-service auth + +--- + +## Quick Start Workflow + +### 1. Install SDK + +```bash +npm install express-openid-connect dotenv +``` + +### 2. Configure Environment + +**For automated setup with Auth0 CLI**, see [Setup Guide](references/setup.md) for complete scripts. + +**For manual setup:** + +Create `.env`: + +```bash +SECRET= +BASE_URL=http://localhost:3000 +CLIENT_ID=your-client-id +CLIENT_SECRET=your-client-secret +ISSUER_BASE_URL=https://your-tenant.auth0.com +``` + +Generate secret: `openssl rand -hex 32` + +### 3. Configure Auth Middleware + +Update your Express app (`app.js` or `index.js`): + +```javascript +require('dotenv').config(); +const express = require('express'); +const { auth, requiresAuth } = require('express-openid-connect'); + +const app = express(); + +// Configure Auth0 middleware +app.use(auth({ + authRequired: false, // Don't require auth for all routes + auth0Logout: true, // Enable logout endpoint + secret: process.env.SECRET, + baseURL: process.env.BASE_URL, + clientID: process.env.CLIENT_ID, + issuerBaseURL: process.env.ISSUER_BASE_URL, + clientSecret: process.env.CLIENT_SECRET +})); + +app.listen(3000, () => { + console.log('Server running on http://localhost:3000'); +}); +``` + +This automatically creates: +- `/login` - Login endpoint +- `/logout` - Logout endpoint +- `/callback` - OAuth callback + +### 4. Add Routes + +```javascript +// Public route +app.get('/', (req, res) => { + res.send(req.oidc.isAuthenticated() ? 'Logged in' : 'Logged out'); +}); + +// Protected route +app.get('/profile', requiresAuth(), (req, res) => { + res.send(` +

Profile

+

Name: ${req.oidc.user.name}

+

Email: ${req.oidc.user.email}

+
${JSON.stringify(req.oidc.user, null, 2)}
+ Logout + `); +}); + +// Login/logout links +app.get('/', (req, res) => { + res.send(` + ${req.oidc.isAuthenticated() ? ` +

Welcome, ${req.oidc.user.name}!

+ Profile + Logout + ` : ` + Login + `} + `); +}); +``` + +### 5. Test Authentication + +Start your server: + +```bash +node app.js +``` + +Visit `http://localhost:3000` and test the login flow. + +--- + +## Detailed Documentation + +- **[Setup Guide](references/setup.md)** - Automated setup scripts, environment configuration, Auth0 CLI usage +- **[Integration Guide](references/integration.md)** - Protected routes, sessions, API integration, error handling +- **[API Reference](references/api.md)** - Complete middleware API, configuration options, request properties + +--- + +## Common Mistakes + +| Mistake | Fix | +|---------|-----| +| Forgot to add callback URL in Auth0 Dashboard | Add `/callback` path to Allowed Callback URLs (e.g., `http://localhost:3000/callback`) | +| Missing or weak SECRET | Generate secure secret with `openssl rand -hex 32` and store in .env as `SECRET` | +| Setting authRequired: true globally | Set to false and use `requiresAuth()` middleware on specific routes | +| App created as SPA type in Auth0 | Must be Regular Web Application type for server-side auth | +| Session secret exposed in code | Always use environment variables, never hardcode secrets | +| Wrong baseURL for production | Update BASE_URL to match your production domain | +| Not handling logout returnTo | Add your domain to Allowed Logout URLs in Auth0 Dashboard | + +--- + +## Related Skills + +- `auth0-quickstart` - Basic Auth0 setup +- `auth0-migration` - Migrate from another auth provider +- `auth0-mfa` - Add Multi-Factor Authentication + +--- + +## Quick Reference + +**Middleware Options:** +- `authRequired` - Require auth for all routes (default: false) +- `auth0Logout` - Enable /logout endpoint (default: false) +- `secret` - Session secret (required) +- `baseURL` - Application URL (required) +- `clientID` - Auth0 client ID (required) +- `issuerBaseURL` - Auth0 tenant URL (required) + +**Request Properties:** +- `req.oidc.isAuthenticated()` - Check if user is logged in +- `req.oidc.user` - User profile object +- `req.oidc.accessToken` - Access token for API calls +- `req.oidc.idToken` - ID token +- `req.oidc.refreshToken` - Refresh token + +**Common Use Cases:** +- Protected routes → Use `requiresAuth()` middleware (see Step 4) +- Check auth status → `req.oidc.isAuthenticated()` +- Get user info → `req.oidc.user` +- Call APIs → [Integration Guide](references/integration.md#calling-apis) + +--- + +## References + +- [Express OpenID Connect Documentation](https://auth0.com/docs/libraries/express-openid-connect) +- [Auth0 Express Quickstart](https://auth0.com/docs/quickstart/webapp/express) +- [SDK GitHub Repository](https://github.com/auth0/express-openid-connect) diff --git a/main/.mintlify/skills/auth0-fastify-api/SKILL.md b/main/.mintlify/skills/auth0-fastify-api/SKILL.md new file mode 100644 index 0000000000..1fadcf3c9b --- /dev/null +++ b/main/.mintlify/skills/auth0-fastify-api/SKILL.md @@ -0,0 +1,176 @@ +--- +name: auth0-fastify-api +description: Use when securing Fastify API endpoints with JWT Bearer token validation, scope/permission checks, or stateless auth - integrates @auth0/auth0-fastify-api for REST APIs receiving access tokens from frontends or mobile apps. +license: Apache-2.0 +metadata: + author: Auth0 +--- + +# Auth0 Fastify API Integration + +Protect Fastify API endpoints with JWT access token validation using @auth0/auth0-fastify-api. + +--- + +## Prerequisites + +- Fastify API application (v5.x or newer) +- Node.js 20 LTS or newer +- Auth0 API configured (not Application - must be API resource) +- If you don't have Auth0 set up yet, use the `auth0-quickstart` skill first + +## When NOT to Use + +- **Server-rendered web applications** - Use `@auth0/auth0-fastify` for session-based auth +- **Single Page Applications** - Use `auth0-react`, `auth0-vue`, or `auth0-angular` for client-side auth +- **Next.js applications** - Use `auth0-nextjs` skill +- **Mobile applications** - Use `auth0-react-native` for React Native/Expo + +--- + +## Quick Start Workflow + +### 1. Install SDK + +```bash +npm install @auth0/auth0-fastify-api fastify dotenv +``` + +### 2. Create Auth0 API + +You need an **API** (not Application) in Auth0: + +```bash +# Using Auth0 CLI +auth0 apis create \ + --name "My Fastify API" \ + --identifier https://my-api.example.com +``` + +Or create manually in Auth0 Dashboard → Applications → APIs + +### 3. Configure Environment + +Create `.env`: + +```bash +AUTH0_DOMAIN=your-tenant.auth0.com +AUTH0_AUDIENCE=https://my-api.example.com +``` + +### 4. Configure Auth Plugin + +Create your Fastify server (`server.js`): + +```javascript +import 'dotenv/config'; +import Fastify from 'fastify'; +import fastifyAuth0Api from '@auth0/auth0-fastify-api'; + +const fastify = Fastify({ logger: true }); + +// Register Auth0 API plugin +await fastify.register(fastifyAuth0Api, { + domain: process.env.AUTH0_DOMAIN, + audience: process.env.AUTH0_AUDIENCE, +}); + +fastify.listen({ port: 3001 }); +``` + +### 5. Protect Routes + +```javascript +// Public route - no authentication +fastify.get('/api/public', async (request, reply) => { + return { + message: 'Hello from a public endpoint!', + timestamp: new Date().toISOString(), + }; +}); + +// Protected route - requires valid JWT +fastify.get('/api/private', { + preHandler: fastify.requireAuth() +}, async (request, reply) => { + return { + message: 'Hello from a protected endpoint!', + user: request.user.sub, + timestamp: new Date().toISOString(), + }; +}); + +// Protected route with user info +fastify.get('/api/profile', { + preHandler: fastify.requireAuth() +}, async (request, reply) => { + return { + profile: request.user, // JWT claims + }; +}); +``` + +### 6. Test API + +Test public endpoint: + +```bash +curl http://localhost:3001/api/public +``` + +Test protected endpoint (requires access token): + +```bash +curl http://localhost:3001/api/private \ + -H "Authorization: Bearer YOUR_ACCESS_TOKEN" +``` + +--- + +## Common Mistakes + +| Mistake | Fix | +|---------|-----| +| Created Application instead of API in Auth0 | Must create API resource in Auth0 Dashboard → Applications → APIs | +| Missing Authorization header | Include `Authorization: Bearer ` in all protected endpoint requests | +| Wrong audience in token | Client must request token with matching `audience` parameter | +| Using ID token instead of access token | Must use **access token** for API auth, not ID token | +| Not handling 401/403 errors | Implement proper error handling for unauthorized/forbidden responses | + +--- + +## Related Skills + +- `auth0-quickstart` - Basic Auth0 setup +- `auth0-fastify` - For server-rendered Fastify web apps with sessions +- `auth0-mfa` - Add Multi-Factor Authentication + +--- + +## Quick Reference + +**Plugin Options:** +- `domain` - Auth0 tenant domain (required) +- `audience` - API identifier from Auth0 API settings (required) + +**Request Properties:** +- `request.user` - Decoded JWT claims object +- `request.user.sub` - User ID (subject) + +**Middleware:** +- `fastify.requireAuth()` - Protect route with JWT validation +- `fastify.requireAuth({ scopes: 'read:data' })` - Require specific scope +- `fastify.requireAuth({ scopes: ['read:data', 'write:data'] })` - Require specific scopes + +**Common Use Cases:** +- Protect routes → Use `preHandler: fastify.requireAuth()` (see Step 5) +- Get user ID → `request.user.sub` +- Custom claims → Access via `request.user['namespace/claim']` + +--- + +## References + +- [Auth0 Fastify API Documentation](https://auth0.com/docs/quickstart/backend/fastify) +- [SDK GitHub Repository](https://github.com/auth0/auth0-fastify) +- [Access Tokens Guide](https://auth0.com/docs/secure/tokens/access-tokens) diff --git a/main/.mintlify/skills/auth0-fastify/SKILL.md b/main/.mintlify/skills/auth0-fastify/SKILL.md new file mode 100644 index 0000000000..466fd4ba42 --- /dev/null +++ b/main/.mintlify/skills/auth0-fastify/SKILL.md @@ -0,0 +1,175 @@ +--- +name: auth0-fastify +description: Use when adding authentication (login, logout, protected routes) to Fastify web applications - integrates @auth0/auth0-fastify for session-based auth. For stateless Fastify APIs use auth0-fastify-api instead. +license: Apache-2.0 +metadata: + author: Auth0 +--- + +# Auth0 Fastify Integration + +Add authentication to Fastify web applications using @auth0/auth0-fastify. + +--- + +## Prerequisites + +- Fastify application (v5.x or newer) +- Node.js 20 LTS or newer +- Auth0 account and application configured +- If you don't have Auth0 set up yet, use the `auth0-quickstart` skill first + +## When NOT to Use + +- **Single Page Applications** - Use `auth0-react`, `auth0-vue`, or `auth0-angular` for client-side auth +- **Next.js applications** - Use `auth0-nextjs` skill which handles both client and server +- **Mobile applications** - Use `auth0-react-native` for React Native/Expo +- **Stateless APIs** - Use `@auth0/auth0-fastify-api` instead for JWT validation without sessions +- **Microservices** - Use JWT validation for service-to-service auth + +--- + +## Quick Start Workflow + +### 1. Install SDK + +```bash +npm install @auth0/auth0-fastify fastify @fastify/view ejs dotenv +``` + +### 2. Configure Environment + +Create `.env`: + +```bash +AUTH0_DOMAIN=your-tenant.auth0.com +AUTH0_CLIENT_ID=your-client-id +AUTH0_CLIENT_SECRET=your-client-secret +SESSION_SECRET= +APP_BASE_URL=http://localhost:3000 +``` + +Generate secret: `openssl rand -hex 64` + +### 3. Configure Auth Plugin + +Create your Fastify server (`server.js`): + +```javascript +import 'dotenv/config'; +import Fastify from 'fastify'; +import fastifyAuth0 from '@auth0/auth0-fastify'; +import fastifyView from '@fastify/view'; +import ejs from 'ejs'; + +const fastify = Fastify({ logger: true }); + +// Register view engine +await fastify.register(fastifyView, { + engine: { ejs }, + root: './views', +}); + +// Configure Auth0 plugin +await fastify.register(fastifyAuth0, { + domain: process.env.AUTH0_DOMAIN, + clientId: process.env.AUTH0_CLIENT_ID, + clientSecret: process.env.AUTH0_CLIENT_SECRET, + appBaseUrl: process.env.APP_BASE_URL, + sessionSecret: process.env.SESSION_SECRET, +}); + +fastify.listen({ port: 3000 }); +``` + +This automatically creates: +- `/auth/login` - Login endpoint +- `/auth/logout` - Logout endpoint +- `/auth/callback` - OAuth callback + +### 4. Add Routes + +```javascript +// Public route +fastify.get('/', async (request, reply) => { + const session = await fastify.auth0Client.getSession({ request, reply }); + return reply.view('views/home.ejs', { + isAuthenticated: !!session, + }); +}); + +// Protected route +fastify.get('/profile', { + preHandler: async (request, reply) => { + const session = await fastify.auth0Client.getSession({ request, reply }); + if (!session) { + return reply.redirect('/auth/login'); + } + } +}, async (request, reply) => { + const user = await fastify.auth0Client.getUser({ request, reply }); + return reply.view('views/profile.ejs', { user }); +}); +``` + +### 5. Test Authentication + +Start your server: + +```bash +node server.js +``` + +Visit `http://localhost:3000` and test the login flow. + +--- + +## Common Mistakes + +| Mistake | Fix | +|---------|-----| +| Forgot to add callback URL in Auth0 Dashboard | Add `/auth/callback` path to Allowed Callback URLs (e.g., `http://localhost:3000/auth/callback`) | +| Missing or weak SESSION_SECRET | Generate secure 64-char secret with `openssl rand -hex 64` and store in .env | +| App created as SPA type in Auth0 | Must be Regular Web Application type for server-side auth | +| Session secret exposed in code | Always use environment variables, never hardcode secrets | +| Wrong appBaseUrl for production | Update APP_BASE_URL to match your production domain | +| Not awaiting fastify.register | Fastify v4+ requires awaiting plugin registration | + +--- + +## Related Skills + +- `auth0-quickstart` - Basic Auth0 setup +- `auth0-migration` - Migrate from another auth provider +- `auth0-mfa` - Add Multi-Factor Authentication + +--- + +## Quick Reference + +**Plugin Options:** +- `domain` - Auth0 tenant domain (required) +- `clientId` - Auth0 client ID (required) +- `clientSecret` - Auth0 client secret (required) +- `appBaseUrl` - Application URL (required) +- `sessionSecret` - Session encryption secret (required, min 64 chars) +- `audience` - API audience (optional, for calling APIs) + +**Client Methods:** +- `fastify.auth0Client.getSession({ request, reply })` - Get user session +- `fastify.auth0Client.getUser({ request, reply })` - Get user profile +- `fastify.auth0Client.getAccessToken({ request, reply })` - Get access token +- `fastify.auth0Client.logout(options, { request, reply })` - Logout user + +**Common Use Cases:** +- Protected routes → Use `preHandler` to check session (see Step 4) +- Check auth status → `!!session` +- Get user info → `getUser({ request, reply })` +- Call APIs → `getAccessToken({ request, reply })` + +--- + +## References + +- [Auth0 Fastify Documentation](https://auth0.com/docs/quickstart/webapp/fastify) +- [SDK GitHub Repository](https://github.com/auth0/auth0-fastify) diff --git a/main/.mintlify/skills/auth0-mfa/SKILL.md b/main/.mintlify/skills/auth0-mfa/SKILL.md new file mode 100644 index 0000000000..77efe88e34 --- /dev/null +++ b/main/.mintlify/skills/auth0-mfa/SKILL.md @@ -0,0 +1,172 @@ +--- +name: auth0-mfa +description: Use when adding MFA, 2FA, TOTP, SMS codes, push notifications, passkeys, or when requiring step-up verification for sensitive operations or meeting compliance requirements (HIPAA, PCI-DSS) - covers adaptive and risk-based authentication with Auth0. +license: Apache-2.0 +metadata: + author: Auth0 +--- + +# Auth0 MFA Guide + +Add Multi-Factor Authentication to protect user accounts and require additional verification for sensitive operations. + +--- + +## Overview + +### What is MFA? + +Multi-Factor Authentication (MFA) requires users to provide two or more verification factors to access their accounts. Auth0 supports multiple MFA factors and enables step-up authentication for sensitive operations. + +### When to Use This Skill + +- Adding MFA to protect user accounts +- Requiring additional verification for sensitive actions (payments, settings changes) +- Implementing adaptive/risk-based authentication +- Meeting compliance requirements (PCI-DSS, SOC2, HIPAA) + +### MFA Factors Supported + +| Factor | Type | Description | +|--------|------|-------------| +| TOTP | Something you have | Time-based one-time passwords (Google Authenticator, Authy) | +| SMS | Something you have | One-time codes via text message | +| Email | Something you have | One-time codes via email | +| Push | Something you have | Push notifications via Auth0 Guardian app | +| WebAuthn | Something you have/are | Security keys, biometrics, passkeys | +| Voice | Something you have | One-time codes via phone call | +| Recovery Code | Backup | One-time use recovery codes | + +### Key Concepts + +| Concept | Description | +|---------|-------------| +| `acr_values` | Request MFA during authentication | +| `amr` claim | Authentication Methods Reference - indicates how user authenticated | +| Step-up auth | Require MFA for specific actions after initial login | +| Adaptive MFA | Conditionally require MFA based on risk signals | + +--- + +## Step 1: Enable MFA in Tenant + +### Via Auth0 Dashboard + +1. Go to **Security → Multi-factor Auth** +2. Enable desired factors (TOTP, SMS, etc.) +3. Configure **Policies**: + - **Always** - Require MFA for all logins + - **Adaptive** - Risk-based MFA + - **Never** - Disable MFA (use step-up instead) + +### Via Auth0 CLI + +```bash +# View current MFA configuration +auth0 api get "guardian/factors" + +# Enable TOTP (One-time Password) +auth0 api put "guardian/factors/otp" --data '{"enabled": true}' + +# Enable SMS +auth0 api put "guardian/factors/sms" --data '{"enabled": true}' + +# Enable Push notifications +auth0 api put "guardian/factors/push-notification" --data '{"enabled": true}' + +# Enable WebAuthn (Roaming - Security Keys) +auth0 api put "guardian/factors/webauthn-roaming" --data '{"enabled": true}' + +# Enable WebAuthn (Platform - Biometrics) +auth0 api put "guardian/factors/webauthn-platform" --data '{"enabled": true}' + +# Enable Email +auth0 api put "guardian/factors/email" --data '{"enabled": true}' +``` + +### Configure MFA Policy + +```bash +# Set MFA policy: "all-applications" or "confidence-score" +auth0 api patch "guardian/policies" --data '["all-applications"]' +``` + +--- + +## Step 2: Implement Step-Up Authentication + +Step-up auth requires MFA for sensitive operations without requiring it for every login. + +### The `acr_values` Parameter + +Request MFA by including `acr_values` in your authorization request: + +``` +acr_values=http://schemas.openid.net/pape/policies/2007/06/multi-factor +``` + +### Implementation Pattern + +The general pattern for all frameworks: + +1. Check if user has already completed MFA (inspect `amr` claim) +2. If not, request MFA via `acr_values` parameter +3. Proceed with sensitive action once MFA is verified + +**For complete framework-specific examples, see [Examples Guide](references/examples.md):** +- React (basic and custom hook) +- Next.js (App Router) +- Vue.js +- Angular + +--- + +## Additional Resources + +This skill is split into multiple files for better organization: + +### [Step-Up Examples](references/examples.md) +Complete code examples for all frameworks: +- React (basic and custom hook patterns) +- Next.js (App Router with API routes) +- Vue.js (composition API) +- Angular (services and components) + +### [Backend Validation](references/backend.md) +Learn how to validate MFA status on your backend: +- Node.js / Express JWT validation +- Python / Flask validation +- Middleware examples + +### [Advanced Topics](references/advanced.md) +Advanced MFA implementation patterns: +- Adaptive MFA with Auth0 Actions +- Conditional MFA based on risk signals +- MFA Enrollment API + +### [Reference Guide](references/api.md) +Common patterns and troubleshooting: +- Remember MFA for 30 days +- MFA for high-value transactions +- MFA status display +- Error handling +- AMR claim values +- Testing strategies +- Security considerations + +--- + +## Related Skills + +- `auth0-quickstart` - Basic Auth0 setup +- `auth0-passkeys` - WebAuthn/passkey implementation +- `auth0-actions` - Custom authentication logic + +--- + +## References + +- [Auth0 MFA Documentation](https://auth0.com/docs/secure/multi-factor-authentication) +- [Step-Up Authentication](https://auth0.com/docs/secure/multi-factor-authentication/step-up-authentication) +- [MFA API](https://auth0.com/docs/secure/multi-factor-authentication/manage-mfa-auth0-apis) +- [acr_values Parameter](https://auth0.com/docs/get-started/authentication-and-authorization-flow/authorization-code-flow/add-login-auth-code-flow#request-parameters) diff --git a/main/.mintlify/skills/auth0-migration/SKILL.md b/main/.mintlify/skills/auth0-migration/SKILL.md new file mode 100644 index 0000000000..a39d4fd27f --- /dev/null +++ b/main/.mintlify/skills/auth0-migration/SKILL.md @@ -0,0 +1,245 @@ +--- +name: auth0-migration +description: Use when migrating or switching from an existing auth provider (Firebase, Cognito, Supabase, Clerk, custom auth) to Auth0 - covers bulk user import, gradual migration strategies, code migration patterns, and JWT validation updates. +license: Apache-2.0 +metadata: + author: Auth0 +--- + +# Auth0 Migration Guide + +Migrate users and authentication flows from existing auth providers to Auth0. + +--- + +## Overview + +### When to Use This Skill + +- Migrating from another auth provider to Auth0 +- Bulk importing existing users +- Gradually transitioning active user bases +- Updating JWT validation in APIs + +## When NOT to Use + +- **Starting fresh with Auth0** - Use `auth0-quickstart` for new projects without existing users +- **Already using Auth0** - This is for migrating TO Auth0, not between Auth0 tenants +- **Only adding MFA or features** - Use feature-specific skills if just adding capabilities + +### Migration Approaches + +- **Bulk Migration:** One-time user import (recommended for small/inactive bases) +- **Gradual Migration:** Lazy migration over time (recommended for large active bases) +- **Hybrid:** Import inactive users, lazy-migrate active users + +--- + +## Step 0: Detect Existing Auth Provider + +**Check if the project already has authentication:** + +Search for common auth-related patterns in the codebase: + +| Pattern | Indicates | +|---------|-----------| +| `signInWithEmailAndPassword`, `onAuthStateChanged` | Firebase Auth | +| `useUser`, `useSession`, `isSignedIn` | Existing auth hooks | +| `passport.authenticate`, `LocalStrategy` | Passport.js | +| `authorize`, `getAccessToken`, `oauth` | OAuth/OIDC | +| `JWT`, `jwt.verify`, `jsonwebtoken` | Token-based auth | +| `/api/auth/`, `/login`, `/callback` | Auth routes | + +**If existing auth detected, ask:** + +> I detected existing authentication in your project. Are you: +> 1. **Migrating to Auth0** (replace existing auth) +> 2. **Adding Auth0 alongside** (keep both temporarily) +> 3. **Starting fresh** (remove old auth, new Auth0 setup) + +--- + +## Migration Workflow + +### Step 1: Export Existing Users + +Export users from your current provider. See [User Import Guide](references/user-import.md) for detailed instructions: +- [Exporting from Firebase](references/user-import.md#firebase) +- [Exporting from AWS Cognito](references/user-import.md#aws-cognito) +- [Exporting from Supabase](references/user-import.md#supabase) +- [Exporting from Custom Database](references/user-import.md#custom-database) + +**Required data per user:** +- Email address +- Email verified status +- Password hash (if available) +- User metadata/profile data +- Creation timestamp + +--- + +### Step 2: Import Users to Auth0 + +Import users via Dashboard, CLI, or Management API. + +**Quick start:** +```bash +# Via Auth0 CLI +auth0 api post "jobs/users-imports" \ + --data "connection_id=con_ABC123" \ + --data "users=@users.json" +``` + +**For detailed instructions:** +- [User JSON Format](references/user-import.md#auth0-user-import-format) +- [Password Hash Algorithms](references/user-import.md#password-hash-algorithms) +- [Import Methods](references/user-import.md#importing-to-auth0) +- [Monitoring Import Progress](references/user-import.md#monitoring-import-progress) +- [Common Import Errors](references/user-import.md#common-import-errors) + +--- + +### Step 3: Migrate Application Code + +Update your application code to use Auth0 SDKs. + +**See [Code Migration Patterns](references/code-patterns.md) for detailed before/after examples:** + +**Frontend:** +- [React Migration](references/code-patterns.md#react-migration) +- [Next.js Migration](references/code-patterns.md#nextjs-migration) +- [Vue.js Migration](references/code-patterns.md#vuejs-migration) +- [Angular Migration](references/code-patterns.md#angular-migration) +- [React Native Migration](references/code-patterns.md#react-native-migration) + +**Backend:** +- [Express.js Migration](references/code-patterns.md#expressjs-migration) +- [API JWT Validation](references/code-patterns.md#backend-api-jwt-validation) + +**Provider-Specific:** +- [Firebase to Auth0](references/code-patterns.md#firebase-to-auth0) +- [Supabase to Auth0](references/code-patterns.md#supabase-to-auth0) +- [Clerk to Auth0](references/code-patterns.md#clerk-to-auth0) + +**After migrating code, use framework-specific skills:** +- `auth0-react` for React applications +- `auth0-nextjs` for Next.js applications +- `auth0-vue` for Vue.js applications +- `auth0-angular` for Angular applications +- `auth0-express` for Express.js applications +- `auth0-react-native` for React Native/Expo applications + +--- + +### Step 4: Update API JWT Validation + +If your API validates JWTs, update to validate Auth0 tokens. + +**Key differences:** +- **Algorithm:** HS256 (symmetric) → RS256 (asymmetric) +- **Issuer:** Custom → `https://YOUR_TENANT.auth0.com/` +- **JWKS URL:** `https://YOUR_TENANT.auth0.com/.well-known/jwks.json` + +**See [JWT Validation Examples](references/code-patterns.md#backend-api-jwt-validation) for:** +- Node.js / Express implementation +- Python / Flask implementation +- Key differences and migration checklist + +--- + +## Gradual Migration Strategy + +For production applications with active users, use a phased approach: + +### Phase 1: Parallel Auth + +Support both Auth0 and legacy provider simultaneously: + +```typescript +// Support both providers during migration +const getUser = async () => { + // Try Auth0 first + const auth0User = await getAuth0User(); + if (auth0User) return auth0User; + + // Fall back to legacy provider + return await getLegacyUser(); +}; +``` + +### Phase 2: New Users on Auth0 + +- All new signups go to Auth0 +- Existing users continue on legacy provider +- Migrate users on next login (lazy migration) + +### Phase 3: Forced Migration + +- Prompt remaining users to "update account" +- Send password reset emails via Auth0 +- Set deadline for legacy system shutdown + +### Phase 4: Cleanup + +- Remove legacy auth code +- Archive user export for compliance +- Update documentation + +--- + +## Common Migration Issues + +| Issue | Solution | +|-------|----------| +| Password hashes incompatible | Use Auth0 custom DB connection with lazy migration | +| Social logins don't link | Configure same social connection, users auto-link by email | +| Custom claims missing | Add claims via Auth0 Actions | +| Token format different | Update API to validate RS256 JWTs with Auth0 issuer | +| Session persistence | Auth0 uses rotating refresh tokens; update token storage | +| Users must re-login | Expected for redirect-based auth; communicate to users | + +--- + +## Reference Documentation + +### User Import +Complete guide to exporting and importing users: +- [Exporting from Common Providers](references/user-import.md#exporting-users-from-common-providers) +- [User JSON Format](references/user-import.md#auth0-user-import-format) +- [Password Hash Algorithms](references/user-import.md#password-hash-algorithms) +- [Import Methods](references/user-import.md#importing-to-auth0) +- [Monitoring & Troubleshooting](references/user-import.md#monitoring-import-progress) + +### Code Migration +Before/after examples for all major frameworks: +- [React Patterns](references/code-patterns.md#react-migration) +- [Next.js Patterns](references/code-patterns.md#nextjs-migration) +- [Express Patterns](references/code-patterns.md#expressjs-migration) +- [Vue.js Patterns](references/code-patterns.md#vuejs-migration) +- [Angular Patterns](references/code-patterns.md#angular-migration) +- [React Native Patterns](references/code-patterns.md#react-native-migration) +- [API JWT Validation](references/code-patterns.md#backend-api-jwt-validation) + +--- + +## Related Skills + +### Core Integration +- `auth0-quickstart` - Initial Auth0 setup after migration + +### SDK Skills +- `auth0-react` - React SPA integration +- `auth0-nextjs` - Next.js integration +- `auth0-vue` - Vue.js integration +- `auth0-angular` - Angular integration +- `auth0-express` - Express.js integration +- `auth0-react-native` - React Native/Expo integration + +--- + +## References + +- [Auth0 User Migration Documentation](https://auth0.com/docs/manage-users/user-migration) +- [Bulk User Import](https://auth0.com/docs/manage-users/user-migration/bulk-user-imports) +- [Password Hash Algorithms](https://auth0.com/docs/manage-users/user-migration/bulk-user-imports#password-hashing-algorithms) +- [Management API - User Import](https://auth0.com/docs/api/management/v2/jobs/post-users-imports) diff --git a/main/.mintlify/skills/auth0-nextjs/SKILL.md b/main/.mintlify/skills/auth0-nextjs/SKILL.md new file mode 100644 index 0000000000..8dadd36116 --- /dev/null +++ b/main/.mintlify/skills/auth0-nextjs/SKILL.md @@ -0,0 +1,282 @@ +--- +name: auth0-nextjs +description: Use when adding authentication to Next.js applications (login, logout, protected pages, middleware, server components) - supports App Router and Pages Router with @auth0/nextjs-auth0 SDK. +license: Apache-2.0 +metadata: + author: Auth0 +--- + +# Auth0 Next.js Integration + +Add authentication to Next.js applications using @auth0/nextjs-auth0. Supports both App Router and Pages Router. + +--- + +## Prerequisites + +- Next.js 13+ application (App Router or Pages Router) +- Auth0 account and application configured +- If you don't have Auth0 set up yet, use the `auth0-quickstart` skill first + +## When NOT to Use + +- **Client-side only React apps** - Use `auth0-react` for Vite/CRA SPAs +- **React Native mobile apps** - Use `auth0-react-native` for iOS/Android +- **Non-Next.js frameworks** - Use framework-specific SDKs (Express, Vue, Angular, etc.) +- **Stateless APIs only** - Use JWT validation middleware if you don't need session management + +--- + +## Quick Start Workflow + +### 1. Install SDK + +```bash +npm install @auth0/nextjs-auth0 +``` + +### 2. Configure Environment + +**For automated setup with Auth0 CLI**, see [Setup Guide](references/setup.md) for complete scripts. + +**For manual setup:** + +Create `.env.local`: + +```bash +AUTH0_SECRET= +APP_BASE_URL=http://localhost:3000 +AUTH0_DOMAIN=your-tenant.auth0.com +AUTH0_CLIENT_ID=your-client-id +AUTH0_CLIENT_SECRET=your-client-secret +``` + +Generate secret: `openssl rand -hex 32` + +**Important:** Add `.env.local` to `.gitignore` + +### 3. Create Auth0 Client and Middleware + +**Detect project structure first:** Check whether the project uses a `src/` directory (i.e. `src/app/` or `src/pages/` exists). This determines where to place files: +- **With `src/`:** `src/lib/auth0.ts`, `src/middleware.ts` (or `src/proxy.ts` for Next.js 16) +- **Without `src/`:** `lib/auth0.ts`, `middleware.ts` (or `proxy.ts` for Next.js 16) + +Create `lib/auth0.ts` (or `src/lib/auth0.ts` if using the `src/` convention): + +```typescript +import { Auth0Client } from '@auth0/nextjs-auth0/server'; + +export const auth0 = new Auth0Client({ + domain: process.env.AUTH0_DOMAIN!, + clientId: process.env.AUTH0_CLIENT_ID!, + clientSecret: process.env.AUTH0_CLIENT_SECRET!, + secret: process.env.AUTH0_SECRET!, + appBaseUrl: process.env.APP_BASE_URL!, +}); +``` + +**Middleware Configuration (Next.js 15 vs 16):** + +**Next.js 15** - Create `middleware.ts` (at project root, or `src/middleware.ts` if using `src/`): + +```typescript +import { NextRequest } from 'next/server'; +import { auth0 } from '@/lib/auth0'; + +export async function middleware(request: NextRequest) { + return await auth0.middleware(request); +} + +export const config = { + matcher: [ + '/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)', + ], +}; +``` + +**Next.js 16** - You have two options: + +**Option 1:** Use `middleware.ts` (same as Next.js 15, same `src/` placement rules): + +```typescript +import { NextRequest } from 'next/server'; +import { auth0 } from '@/lib/auth0'; + +export async function middleware(request: NextRequest) { + return await auth0.middleware(request); +} + +export const config = { + matcher: [ + '/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)', + ], +}; +``` + +**Option 2:** Use `proxy.ts` (at project root, or `src/proxy.ts` if using `src/`): + +```typescript +import { NextRequest } from 'next/server'; +import { auth0 } from '@/lib/auth0'; + +export async function proxy(request: NextRequest) { + return await auth0.middleware(request); +} + +export const config = { + matcher: [ + '/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)', + ], +}; +``` + +This automatically creates endpoints: +- `/auth/login` - Login +- `/auth/logout` - Logout +- `/auth/callback` - OAuth callback +- `/auth/profile` - User profile + +### 4. Add User Context (Optional) + +**Note:** In v4, wrapping with `` is optional. Only needed if you want to pass an initial user during server rendering to `useUser()`. + +**App Router** - Optionally wrap app in `app/layout.tsx`: + +```typescript +import { Auth0Provider } from '@auth0/nextjs-auth0/client'; +import { auth0 } from '@/lib/auth0'; + +export default async function RootLayout({ children }: { children: React.ReactNode }) { + const session = await auth0.getSession(); + + return ( + + + {children} + + + ); +} +``` + +**Pages Router** - Optionally wrap app in `pages/_app.tsx`: + +```typescript +import { Auth0Provider } from '@auth0/nextjs-auth0/client'; +import type { AppProps } from 'next/app'; + +export default function App({ Component, pageProps }: AppProps) { + return ( + + + + ); +} +``` + +### 5. Add Authentication UI + +**Client Component** (works in both routers): + +```typescript +'use client'; // Only needed for App Router + +import { useUser } from '@auth0/nextjs-auth0/client'; + +export default function Profile() { + const { user, isLoading } = useUser(); + + if (isLoading) return
Loading...
; + + if (user) { + return ( +
+ {user.name} +

Welcome, {user.name}!

+ Logout +
+ ); + } + + return Login; +} +``` + +### 6. Test Authentication + +Start your dev server: + +```bash +npm run dev +``` + +Visit `http://localhost:3000` and test the login flow. + +--- + +## Detailed Documentation + +- **[Setup Guide](references/setup.md)** - Automated setup scripts, environment configuration, Auth0 CLI usage +- **[Integration Guide](references/integration.md)** - Server-side auth, protected routes, API routes, middleware +- **[API Reference](references/api.md)** - Complete SDK API, hooks, helpers, session management + +--- + +## Common Mistakes + +| Mistake | Fix | +|---------|-----| +| Using v3 environment variables | v4 uses `APP_BASE_URL` and `AUTH0_DOMAIN` (not `AUTH0_BASE_URL` or `AUTH0_ISSUER_BASE_URL`) | +| Forgot to add callback URL in Auth0 Dashboard | Add `/auth/callback` to Allowed Callback URLs (e.g., `http://localhost:3000/auth/callback`) | +| Missing middleware configuration | v4 requires middleware to mount auth routes - create `middleware.ts` (Next.js 15+16) or `proxy.ts` (Next.js 16 only) with `auth0.middleware()` | +| Wrong route paths | v4 uses `/auth/login` not `/api/auth/login` - routes drop the `/api` prefix | +| Missing or weak AUTH0_SECRET | Generate secure secret with `openssl rand -hex 32` and store in .env.local | +| Using .env instead of .env.local | Next.js requires .env.local for local secrets, and .env.local should be in .gitignore | +| App created as SPA type in Auth0 | Must be Regular Web Application type for Next.js | +| Using removed v3 helpers | v4 removed `withPageAuthRequired` and `withApiAuthRequired` - use `getSession()` instead | +| Using useUser in Server Component | useUser is client-only, use `auth0.getSession()` for Server Components | +| AUTH0_DOMAIN includes https:// | v4 `AUTH0_DOMAIN` should be just the domain (e.g., `example.auth0.com`), no scheme | + +--- + +## Related Skills + +- `auth0-quickstart` - Basic Auth0 setup +- `auth0-migration` - Migrate from another auth provider +- `auth0-mfa` - Add Multi-Factor Authentication + +--- + +## Quick Reference + +**V4 Setup:** +- Detect `src/` convention: check if `src/app/` or `src/pages/` exists — place all files inside `src/` if so +- Create `lib/auth0.ts` (or `src/lib/auth0.ts`) with `Auth0Client` instance +- Create middleware configuration (required): + - Next.js 15: `middleware.ts` (or `src/middleware.ts`) with `middleware()` function + - Next.js 16: `middleware.ts` with `middleware()` OR `proxy.ts` with `proxy()` function (same `src/` rules) +- Optional: Wrap with `` for SSR user + +**Client-Side Hooks:** +- `useUser()` - Get user in client components +- `user` - User profile object +- `isLoading` - Loading state + +**Server-Side Methods:** +- `auth0.getSession()` - Get session in Server Components/API routes/middleware +- `auth0.getAccessToken()` - Get access token for calling APIs + +**Common Use Cases:** +- Login/Logout links → Use `/auth/login` and `/auth/logout` paths (see Step 5) +- Protected pages (App Router) → [Integration Guide](references/integration.md#protected-pages-app-router) +- Protected pages (Pages Router) → [Integration Guide](references/integration.md#protected-pages-pages-router) +- API routes with auth → [Integration Guide](references/integration.md#protected-api-routes) +- Middleware protection → [Integration Guide](references/integration.md#middleware) + +--- + +## References + +- [Auth0 Next.js SDK Documentation](https://auth0.com/docs/libraries/nextjs) +- [Auth0 Next.js Quickstart](https://auth0.com/docs/quickstart/webapp/nextjs) +- [SDK GitHub Repository](https://github.com/auth0/nextjs-auth0) diff --git a/main/.mintlify/skills/auth0-nuxt/SKILL.md b/main/.mintlify/skills/auth0-nuxt/SKILL.md new file mode 100644 index 0000000000..0629d52879 --- /dev/null +++ b/main/.mintlify/skills/auth0-nuxt/SKILL.md @@ -0,0 +1,227 @@ +--- +name: auth0-nuxt +description: Use when implementing Auth0 authentication in Nuxt 3/4 applications, configuring session management, protecting routes with middleware, or integrating API access tokens - provides setup patterns, composable usage, and security best practices for the @auth0/auth0-nuxt SDK +license: Apache-2.0 +metadata: + author: Auth0 +--- + +# Auth0 Nuxt SDK + +## Overview + +Server-side session authentication for Nuxt 3/4. NOT the same as @auth0/auth0-vue (client-side SPA). + +**Core principle:** Uses server-side encrypted cookie sessions, not client-side tokens. + +## When to Use + +**Use this when:** +- Building Nuxt 3/4 applications with server-side rendering (Node.js 20 LTS+) +- Need secure session management with encrypted cookies +- Protecting server routes and API endpoints +- Accessing Auth0 Management API or custom APIs + +**Don't use this when:** +- Using Nuxt 2 (not supported - use different Auth0 SDK) +- Building pure client-side SPA without server (use @auth0/auth0-vue instead) +- Using non-Auth0 authentication provider +- Static site generation only (SSG) without server runtime + +## Critical Mistakes to Avoid + +| Mistake | Solution | +|---------|----------| +| Installing `@auth0/auth0-vue` or `@auth0/auth0-spa-js` | Use `@auth0/auth0-nuxt` | +| Auth0 app type "Single Page Application" | Use "Regular Web Application" | +| Env vars: `VITE_AUTH0_*` or `VUE_APP_AUTH0_*` | Use `NUXT_AUTH0_*` prefix | +| Using `useUser()` for security checks | Use `useAuth0(event).getSession()` server-side | +| Missing callback URLs in Auth0 Dashboard | Add `http://localhost:3000/auth/callback` | +| Weak/missing session secret | Generate: `openssl rand -hex 64` | + +## Quick Setup + +```bash +# 1. Install +npm install @auth0/auth0-nuxt + +# 2. Generate secret +openssl rand -hex 64 +``` + +```bash +# 3. .env +NUXT_AUTH0_DOMAIN=your-tenant.auth0.com +NUXT_AUTH0_CLIENT_ID=your-client-id +NUXT_AUTH0_CLIENT_SECRET=your-client-secret +NUXT_AUTH0_SESSION_SECRET= +NUXT_AUTH0_APP_BASE_URL=http://localhost:3000 +NUXT_AUTH0_AUDIENCE=https://your-api # optional +``` + +```typescript +// 4. nuxt.config.ts +export default defineNuxtConfig({ + modules: ['@auth0/auth0-nuxt'], + runtimeConfig: { + auth0: { + domain: '', + clientId: '', + clientSecret: '', + sessionSecret: '', + appBaseUrl: 'http://localhost:3000', + audience: '', // optional + }, + }, +}) +``` + +## Built-in Routes + +The SDK automatically mounts these routes: + +| Route | Method | Purpose | +|-------|--------|---------| +| `/auth/login` | GET | Initiates login flow. Supports `?returnTo=/path` parameter | +| `/auth/callback` | GET | Handles Auth0 callback after login | +| `/auth/logout` | GET | Logs user out and redirects to Auth0 logout | +| `/auth/backchannel-logout` | POST | Receives logout tokens for back-channel logout | + +**Customize:** Pass `routes: { login, callback, logout, backchannelLogout }` or `mountRoutes: false` to module config. + +## Composables + +| Composable | Context | Usage | +|------------|---------|-------| +| `useAuth0(event)` | Server-side | Access `getUser()`, `getSession()`, `getAccessToken()`, `logout()` | +| `useUser()` | Client-side | Display user data only. **Never use for security checks** | + +```typescript +// Server example +const auth0 = useAuth0(event); +const session = await auth0.getSession(); +``` + +```vue + + +