{"id":29630978,"url":"https://github.com/auth0-lab/auth0-hono","last_synced_at":"2025-07-21T11:07:49.130Z","repository":{"id":302130052,"uuid":"1000978775","full_name":"auth0-lab/auth0-hono","owner":"auth0-lab","description":"A lightweight and flexible middleware for the [Hono](https://hono.dev) web framework that simplifies authentication via OpenID Connect (OIDC).","archived":false,"fork":false,"pushed_at":"2025-06-30T17:57:48.000Z","size":321,"stargazers_count":2,"open_issues_count":1,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-06-30T18:48:41.237Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/auth0-lab.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":"CODE-OF-CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-06-12T16:04:58.000Z","updated_at":"2025-06-30T17:57:52.000Z","dependencies_parsed_at":"2025-06-30T18:58:51.708Z","dependency_job_id":null,"html_url":"https://github.com/auth0-lab/auth0-hono","commit_stats":null,"previous_names":["auth0-lab/auth0-hono"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/auth0-lab/auth0-hono","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/auth0-lab%2Fauth0-hono","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/auth0-lab%2Fauth0-hono/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/auth0-lab%2Fauth0-hono/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/auth0-lab%2Fauth0-hono/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/auth0-lab","download_url":"https://codeload.github.com/auth0-lab/auth0-hono/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/auth0-lab%2Fauth0-hono/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":266287824,"owners_count":23905461,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-07-21T11:07:48.288Z","updated_at":"2025-07-21T11:07:49.122Z","avatar_url":"https://github.com/auth0-lab.png","language":"TypeScript","funding_links":[],"categories":["Labs"],"sub_categories":[],"readme":"# Hono Auth0 Middleware\n\nAn Auth0 authentication middleware for [Hono](https://hono.dev) web framework. Built on top of the official [Auth0 SDK](https://www.npmjs.com/package/@auth0/auth0-server-js), this package provides a simple way to secure your Hono applications using Auth0 authentication.\n\n## Installation\n\n```bash\nnpm install @auth0/auth0-hono\n```\n\n## Basic Usage\n\nThe simplest way to secure your Hono application is to implement the middleware at the application level. By default, all routes will require authentication.\n\n```ts\nimport { Hono } from \"hono\";\nimport { auth } from \"@auth0/auth0-hono\";\n\nconst app = new Hono();\n\n// Configure auth middleware with Auth0 options\napp.use(\n  auth({\n    domain: process.env.AUTH0_DOMAIN,\n    clientID: process.env.AUTH0_CLIENT_ID,\n    clientSecret: process.env.AUTH0_CLIENT_SECRET,\n    baseURL: process.env.BASE_URL,\n    session: {\n      secret: \"password_at_least_32_characters_long\",\n    },\n  }),\n);\n\napp.get(\"/\", (c) =\u003e {\n  return c.text(`Hello ${c.var.auth0Client?.getSession(c)?.user?.name}!`);\n});\n\nexport default app;\n```\n\n## Features\n\n- **Auth0 Authentication Flow**: Implements the Auth0 authorization code flow\n- **Session Management**: Built-in session support with configurable cookie settings\n- **Configurable Routes**: Customize login, callback, and logout route paths\n- **Selective Protection**: Choose which routes require authentication with the `authRequired` option\n- **Token Management**: Handles access tokens, ID tokens and refresh tokens\n- **User Information**: Automatically fetches and provides user profile data\n- **Claim-Based Authorization**: Middleware for authorizing based on claims from tokens\n- **PKCE Support**: Implements Proof Key for Code Exchange for enhanced security\n- **Environment Flexibility**: Works across various environments including Node.js, Bun, Cloudflare Workers, and more\n\n## Configuration Options\n\n### Required Configuration\n\n| Option     | Type     | Description                                              |\n| ---------- | -------- | -------------------------------------------------------- |\n| `domain`   | `string` | Auth0 domain (e.g., `your-tenant.auth0.com`)             |\n| `baseURL`  | `string` | Base URL of your application (e.g., `https://myapp.com`) |\n| `clientID` | `string` | Client ID provided by Auth0                              |\n\n### Optional Configuration\n\n| Option                        | Type            | Default     | Description                                                                                                 |\n| ----------------------------- | --------------- | ----------- | ----------------------------------------------------------------------------------------------------------- |\n| `clientSecret`                | `string`        | `undefined` | Client Secret provided by Auth0 (required for most flows)                                                   |\n| `authRequired`                | `boolean`       | `true`      | Whether authentication is required for all routes                                                           |\n| `idpLogout`                   | `boolean`       | `false`     | Whether to perform logout at Auth0 when logging out locally                                                 |\n| `pushedAuthorizationRequests` | `boolean`       | `false`     | Enable Pushed Authorization Requests (PAR)                                                                  |\n| `customRoutes`                | `Array\u003cstring\u003e` | `[]`        | Specify which built-in routes to skip (options: `'login'`, `'callback'`, `'logout'`, `'backchannelLogout'`) |\n| `errorOnRequiredAuth`         | `boolean`       | `false`     | Return 401 if the user is not authenticated                                                                 |\n| `attemptSilentLogin`          | `boolean`       | `false`     | Whether to attempt a silent login                                                                           |\n\n### Routes Configuration\n\nYou can customize the paths for login, callback, logout, and backchannel logout endpoints:\n\n```ts\napp.use(\n  auth({\n    // ...required options\n    routes: {\n      login: \"/custom-login\",\n      callback: \"/auth-callback\",\n      logout: \"/sign-out\",\n      backchannelLogout: \"/backchannel-logout\",\n    },\n  }),\n);\n```\n\n### Session Configuration\n\nThe middleware uses [hono-sessions](https://www.npmjs.com/package/hono-sessions) for session management. You can configure session options or disable sessions entirely:\n\n```ts\napp.use(\n  auth({\n    // ...required options\n    session: {\n      secret: \"your-secure-encryption-key-minimum-32-chars\",\n      sessionCookieName: \"my_session\",\n      cookieOptions: {\n        sameSite: \"Lax\",\n        path: \"/\",\n        httpOnly: true,\n        secure: process.env.NODE_ENV === \"production\",\n      },\n    },\n  }),\n);\n```\n\n### Authorization Parameters\n\nYou can customize the parameters sent to the authorization endpoint:\n\n```ts\napp.use(\n  auth({\n    // ...required options\n    authorizationParams: {\n      response_type: \"code\",\n      scope: \"openid profile email\",\n      response_mode: \"query\",\n    },\n  }),\n);\n```\n\n### Error handling\n\nYou can catch `Auth0Exception` errors and handle them in your application. This is useful for logging or displaying custom error messages.\n\n```js\nimport { Auth0Exception } from \"@auth0/auth0-hono\";\n\napp.onError((err, c) =\u003e {\n  // Handle Auth0-specific errors\n  if (err instanceof Auth0Exception) {\n    console.log(err);\n    if (process.env.NODE_ENV === \"development\") {\n      return err.getResponse();\n    }\n    return c.text(`Authentication Error`, 500);\n  }\n  // Handle other errors\n  return c.text(`Internal Server Error: ${err.message}`, 500);\n});\n```\n\n### Configuration through Environment Variables\n\nYou can configure the middleware using environment variables instead of passing configuration options directly. This is particularly useful for deployment environments where you want to keep sensitive values in environment variables.\n\nThe following environment variables are supported:\n\n| Environment Variable           | Required | Description                                                        |\n| ------------------------------ | -------- | ------------------------------------------------------------------ |\n| `AUTH0_DOMAIN`                 | Yes      | The Auth0 domain (e.g., `your-tenant.auth0.com`)                   |\n| `AUTH0_CLIENT_ID`              | Yes      | The client ID provided by Auth0                                    |\n| `BASE_URL`                     | Yes      | The base URL of your application (e.g., `https://myapp.com`)       |\n| `AUTH0_CLIENT_SECRET`          | No       | The client secret provided by Auth0 (required for most flows)      |\n| `AUTH0_AUDIENCE`               | No       | The API audience identifier for your Auth0 API                     |\n| `AUTH0_SESSION_ENCRYPTION_KEY` | No       | The secret key used for session encryption (minimum 32 characters) |\n\nWhen environment variables are set, they will be used as defaults for the corresponding configuration options. You can still override them by passing explicit values in the configuration object.\n\n**Example using only environment variables:**\n\n```bash\n# .env file\nAUTH0_DOMAIN=your-tenant.auth0.com\nAUTH0_CLIENT_ID=your_client_id\nAUTH0_CLIENT_SECRET=your_client_secret\nBASE_URL=https://localhost:3000\nAUTH0_SESSION_ENCRYPTION_KEY=your_32_character_minimum_secret_key\nAUTH0_AUDIENCE=https://api.yourapp.com\n```\n\n```ts\nimport { Hono } from \"hono\";\nimport { auth } from \"@auth0/auth0-hono\";\n\nconst app = new Hono();\n\n// No configuration object needed - will use environment variables\napp.use(auth());\n\napp.get(\"/\", (c) =\u003e {\n  return c.text(`Hello ${c.var.auth0Client?.getSession(c)?.user?.name}!`);\n});\n```\n\n**Example with mixed configuration (environment + explicit):**\n\n```ts\napp.use(\n  auth({\n    // These will override environment variables if set\n    authRequired: false,\n    routes: {\n      login: \"/custom-login\",\n      callback: \"/auth-callback\",\n    },\n    // Other options like domain, clientID, etc. will use environment variables\n  }),\n);\n```\n\n## Advanced Usage\n\n### Selective Route Protection\n\nOnly protect specific routes:\n\n```ts\nimport { Hono } from \"hono\";\nimport { auth, requiresAuth } from \"@auth0/auth0-hono\";\n\nconst app = new Hono();\n\napp.use(\n  auth({\n    // ...required options\n    authRequired: false,\n  }),\n);\n\n// Public route - no authentication required\napp.get(\"/\", (c) =\u003e {\n  return c.text(\"This is a public page\");\n});\n\n// Protected route - authentication required\napp.use(\"/profile/*\", requiresAuth());\napp.get(\"/profile\", (c) =\u003e {\n  const user = c.var.oidc.user;\n  return c.text(`Hello ${user.name || user.sub}!`);\n});\n```\n\n### Silent Login Attempt\n\nTry to authenticate silently without user interaction:\n\n```ts\nimport { Hono } from \"hono\";\nimport { auth, attemptSilentLogin } from \"@auth0/auth0-hono\";\n\nconst app = new Hono();\n\napp.use(\n  auth({\n    /* ...options */\n    authRequired: false,\n  }),\n);\n\napp.get(\"/\", attemptSilentLogin(), async (c) =\u003e {\n  if (c.var.oidc?.isAuthenticated) {\n    return c.text(`Hello ${c.var.oidc.user.name}!`);\n  }\n\n  return c.text(\"You are not logged in\");\n});\n```\n\n### Advanced Login Options\n\nThe login middleware supports several advanced options:\n\n```ts\nimport { login } from \"@auth0/auth0-hono\";\n\n// Custom login options\napp.get(\"/custom-login\", async (c) =\u003e {\n  return login({\n    // Redirect user to this URL after successful authentication\n    redirectAfterLogin: \"/dashboard\",\n\n    // Additional authorization parameters to send to the identity provider\n    authorizationParams: {\n      prompt: \"consent\",\n      acr_values: \"level2\",\n      login_hint: \"user@example.com\",\n    },\n\n    // Forward specific query parameters from the login request to the authorization request\n    forwardQueryParams: [\"ui_locales\", \"login_hint\", \"campaign\"],\n\n    // Attempt silent authentication (no user interaction)\n    silent: false,\n  })(c);\n});\n```\n\nWith `forwardQueryParams`, you can pass query parameters from the login request to the authorization request. This is useful for:\n\n- Passing UI locale preferences (`ui_locales`)\n- Forwarding login hints to the identity provider\n- Maintaining tracking parameters throughout the authentication flow\n- Supporting custom parameters your identity provider accepts\n\n## Feedback\n\n### Contributing\n\nWe appreciate feedback and contribution to this repo! Before you get started, please see the following:\n\n- [Auth0's general contribution guidelines](https://github.com/auth0/open-source-template/blob/master/GENERAL-CONTRIBUTING.md)\n- [Auth0's code of conduct guidelines](https://github.com/auth0/open-source-template/blob/master/CODE-OF-CONDUCT.md)\n\n### Raise an issue\n\nTo provide feedback or report a bug, please [raise an issue on our issue tracker](https://github.com/auth0-lab/auth0-hono/issues).\n\n### Vulnerability Reporting\n\nPlease do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/responsible-disclosure-policy) details the procedure for disclosing security issues.\n\n---\n\n\u003cp align=\"center\"\u003e\n  \u003cpicture\u003e\n    \u003csource media=\"(prefers-color-scheme: light)\" srcset=\"https://cdn.auth0.com/website/sdks/logos/auth0_light_mode.png\"   width=\"150\"\u003e\n    \u003csource media=\"(prefers-color-scheme: dark)\" srcset=\"https://cdn.auth0.com/website/sdks/logos/auth0_dark_mode.png\" width=\"150\"\u003e\n    \u003cimg alt=\"Auth0 Logo\" src=\"https://cdn.auth0.com/website/sdks/logos/auth0_light_mode.png\" width=\"150\"\u003e\n  \u003c/picture\u003e\n\u003c/p\u003e\n\u003cp align=\"center\"\u003eAuth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout \u003ca href=\"https://auth0.com/why-auth0\"\u003eWhy Auth0?\u003c/a\u003e\u003c/p\u003e\n\u003cp align=\"center\"\u003e\nThis project is licensed under the Apache 2.0 license. See the \u003ca href=\"/LICENSE\"\u003e LICENSE\u003c/a\u003e file for more info.\u003c/p\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fauth0-lab%2Fauth0-hono","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fauth0-lab%2Fauth0-hono","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fauth0-lab%2Fauth0-hono/lists"}