{"id":13343684,"url":"https://github.com/poupryc/authomatic","last_synced_at":"2025-03-12T06:30:23.592Z","repository":{"id":91575768,"uuid":"230113516","full_name":"poupryc/authomatic","owner":"poupryc","description":"🔐 Now Serverless Functions + Auth0","archived":true,"fork":false,"pushed_at":"2020-07-19T03:50:11.000Z","size":37,"stargazers_count":2,"open_issues_count":1,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-10-24T16:49:03.813Z","etag":null,"topics":["auth","auth0","nextjs","now","serverless","zeit"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/poupryc.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2019-12-25T14:25:14.000Z","updated_at":"2023-01-28T12:06:01.000Z","dependencies_parsed_at":null,"dependency_job_id":"732f2577-37f6-463c-871e-4957985c5825","html_url":"https://github.com/poupryc/authomatic","commit_stats":null,"previous_names":["poupryc/authomatic"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/poupryc%2Fauthomatic","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/poupryc%2Fauthomatic/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/poupryc%2Fauthomatic/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/poupryc%2Fauthomatic/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/poupryc","download_url":"https://codeload.github.com/poupryc/authomatic/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243171339,"owners_count":20247876,"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":["auth","auth0","nextjs","now","serverless","zeit"],"created_at":"2024-07-29T19:31:56.951Z","updated_at":"2025-03-12T06:30:23.333Z","avatar_url":"https://github.com/poupryc.png","language":"TypeScript","readme":"# @helloedit/authomatic\n\nAuth0 SDK remix for signing in to your Next.js applications.\n\n## Methods\n\n### Login\n\n```ts\nimport { NowRequest, NowResponse } from \"@now/node\";\n\nimport { auth } from \"../lib/auth\";\n\nexport default async function login(req: NowRequest, res: NowResponse) {\n  await auth\n    .handleLogin({ res, req })\n    .then(({ url }) =\u003e {\n      res.writeHead(302, { Location: url }).end();\n    })\n    .catch(error =\u003e {\n      res.status(500).end(error.message);\n    });\n}\n```\n\n### Callback\n\n```ts\nimport { NowRequest, NowResponse } from \"@now/node\";\n\nimport { auth } from \"../lib/auth\";\n\nexport default async function callback(req: NowRequest, res: NowResponse) {\n  await auth\n    .handleCallback({ req, res })\n    .then(({ redirectTo }) =\u003e {\n      res.writeHead(302, { Location: redirectTo }).end();\n    })\n    .catch(error =\u003e {\n      res.writeHead(500, error).end();\n    });\n}\n```\n\n### Profile\n\n```ts\nimport { NowRequest, NowResponse } from \"@now/node\";\n\nimport { auth } from \"../lib/auth\";\n\nexport default async function me(req: NowRequest, res: NowResponse) {\n  await auth\n    .handleProfile({ req, res })\n    .then(data =\u003e {\n      res.json({ ...data, authenticated: true }).end();\n    })\n    .catch(error =\u003e {\n      res.json({ authenticated: false }).end();\n    });\n}\n```\n\n🎩\n\n---\n\n# @auth0/nextjs-auth0\n\nAuth0 SDK for signing in to your Next.js applications.\n\n\u003e Note: This library is currently in an experimental state and support is best effort.\n\n[![License](https://img.shields.io/:license-mit-blue.svg?style=flat)](https://opensource.org/licenses/MIT)\n\n## Table of Contents\n\n- [Installation](#installation)\n- [Getting Started](#getting-started)\n- [Contributing](#contributing)\n- [Support + Feedback](#support--feedback)\n- [Frequently Asked Questions](#frequently-asked-questions)\n- [Vulnerability Reporting](#vulnerability-reporting)\n- [What is Auth0](#what-is-auth0)\n- [License](#license)\n\n## Installation\n\nUsing [npm](https://npmjs.org):\n\n```sh\nnpm install @auth0/nextjs-auth0\n```\n\nUsing [yarn](https://yarnpkg.com):\n\n```sh\nyarn add @auth0/nextjs-auth0\n```\n\n\u003e Note that this package supports the following versions of Node.js: `^10.13.0 || \u003e=12.0.0`\n\n## Getting Started\n\n### Auth0 Configuration\n\nCreate a **Regular Web Application** in the [Auth0 Dashboard](https://manage.auth0.com/). If you're using an existing application you'll want to verify that the following settings are configured as follows:\n\n- **Json Web Token Signature Algorithm**: `RS256`\n- **OIDC Conformant**: `True`\n\nGo ahead and configure the URLs for your application:\n\n- **Allowed Callback URLs**: http://localhost:3000/api/callback\n- **Allowed Logout URLs**: http://localhost:3000/\n\nTake note of the **Client ID**, **Client Secret** and **Domain** of your application because you'll need it in the next step.\n\n### Runtime Configuration\n\nAnd then create an instance of the Auth0 plugin (eg: under `/utils/auth0.js`):\n\n```js\nimport { initAuth0 } from \"@auth0/nextjs-auth0\";\nimport config from \"./config\";\n\nexport default initAuth0({\n  domain: \"\u003cAUTH0_DOMAIN\u003e\",\n  clientId: \"\u003cAUTH0_CLIENT_ID\u003e\",\n  clientSecret: \"\u003cAUTH0_CLIENT_SECRET\u003e\",\n  scope: \"openid profile\",\n  redirectUri: \"http://localhost:3000/api/callback\",\n  postLogoutRedirectUri: \"http://localhost:3000/\",\n  session: {\n    // The secret used to encrypt the cookie.\n    cookieSecret: \"\u003cRANDOMLY_GENERATED_SECRET\u003e\",\n    // The cookie lifetime (expiration) in seconds. Set to 8 hours by default.\n    cookieLifetime: 60 * 60 * 8,\n    // (Optional) The cookie domain this should run on. Leave it blank to restrict it to your domain.\n    cookieDomain: \"your-domain.com\",\n    // (Optional) SameSite configuration for the session cookie. Defaults to 'lax', but can be changed to 'strict' or 'none'. Set it to false if you want to disable the SameSite setting.\n    cookieSameSite: \"lax\",\n    // (Optional) Store the id_token in the session. Defaults to false.\n    storeIdToken: false,\n    // (Optional) Store the access_token in the session. Defaults to false.\n    storeAccessToken: false,\n    // (Optional) Store the refresh_token in the session. Defaults to false.\n    storeRefreshToken: false\n  },\n  oidcClient: {\n    // (Optional) Configure the timeout in milliseconds for HTTP requests to Auth0.\n    httpTimeout: 2500,\n    // (Optional) Configure the clock tolerance in milliseconds, if the time on your server is running behind.\n    clockTolerance: 10000\n  }\n});\n```\n\n\u003e Note that when you have configured a Custom Domain in your Auth0 account you should be using that domain (eg: `login.acme.com` instead of `acme.auth0.com`) as the AUTH0_DOMAIN. [You might also need to make changes to your Login page](https://auth0.com/docs/custom-domains/additional-configuration).\n\n### Login\n\nIn order to sign in the user we'll first need a link to the login route.\n\n```html\n\u003ca href=\"/api/login\"\u003eLogin\u003c/a\u003e\n```\n\nCreate an [API Route](https://nextjs.org/docs#api-routes) for this route (`/pages/api/login.js`) which uses the client:\n\n```js\nimport auth0 from \"../../utils/auth0\";\n\nexport default async function login(req, res) {\n  try {\n    await auth0.handleLogin(req, res);\n  } catch (error) {\n    console.error(error);\n    res.status(error.status || 400).end(error.message);\n  }\n}\n```\n\nThis will redirect the user to Auth0. After the transaction is completed Auth0 will redirect the user back to your application. This is why the callback route (`/pages/api/callback.js`) needs to be created which will create a session cookie:\n\n```js\nimport auth0 from \"../../utils/auth0\";\n\nexport default async function callback(req, res) {\n  try {\n    await auth0.handleCallback(req, res, { redirectTo: \"/\" });\n  } catch (error) {\n    console.error(error);\n    res.status(error.status || 400).end(error.message);\n  }\n}\n```\n\nYou can optionally send extra parameters to Auth0 to influence the transaction, for example:\n\n- Showing the login page\n- Filling in the user's email address\n- Exposing information to the custom login page (eg: to show the signup tab)\n- Using a custom `state`\n\n```js\nimport auth0 from \"../../utils/auth0\";\n\nexport default async function login(req, res) {\n  try {\n    await auth0.handleLogin(req, res, {\n      authParams: {\n        login_hint: \"foo@acme.com\",\n        ui_locales: \"nl\",\n        scope: \"some other scope\",\n        state: \"a custom state\",\n        foo: \"bar\"\n      }\n    });\n  } catch (error) {\n    console.error(error);\n    res.status(error.status || 400).end(error.message);\n  }\n}\n```\n\n### Logout\n\nFor signing the user out we'll also need a logout link:\n\n```html\n\u003ca href=\"/api/logout\"\u003eLogout\u003c/a\u003e\n```\n\nCreate an [API Route](https://nextjs.org/docs#api-routes) for this route (`/pages/api/logout.js`) which uses the client:\n\n```js\nimport auth0 from \"../../utils/auth0\";\n\nexport default async function logout(req, res) {\n  try {\n    await auth0.handleLogout(req, res);\n  } catch (error) {\n    console.error(error);\n    res.status(error.status || 400).end(error.message);\n  }\n}\n```\n\n### User Profile\n\nIf you want to expose a route which returns the user profile to the client you can create an additional route (eg: `/pages/api/me.js`):\n\n```js\nimport auth0 from \"../../utils/auth0\";\n\nexport default async function me(req, res) {\n  try {\n    await auth0.handleProfile(req, res);\n  } catch (error) {\n    console.error(error);\n    res.status(error.status || 500).end(error.message);\n  }\n}\n```\n\nYou can then load the user after the page has been rendered on the server:\n\n```js\nasync componentDidMount() {\n  const res = await fetch('/api/me');\n  if (res.ok) {\n    this.setState({\n      session: await res.json()\n    })\n  }\n}\n```\n\nIf you need to access the user's session from within an API route or a Server-rendered page you can use `getSession`. Note that this object will also contain the user's `access_token` and `id_token`.\n\n```js\nProfile.getInitialProps = async ({ req, res }) =\u003e {\n  if (typeof window === \"undefined\") {\n    const { user } = await auth0.getSession(req);\n    if (!user) {\n      res.writeHead(302, {\n        Location: \"/api/login\"\n      });\n      res.end();\n      return;\n    }\n\n    return { user };\n  }\n};\n```\n\n### Calling an API\n\nIt's a common pattern to use Next.js API Routes and proxy them to external APIs. When doing so these APIs typically require an `access_token` to be provided. These APIs can then be configured in Auth0.\n\nIn order to get an access_token for an API you'll need to configure the `audience` on the Auth0 plugin and configure it to store the `access_token` in the cookie:\n\n```js\nimport { initAuth0 } from '@auth0/nextjs-auth0';\n\nexport default initAuth0({\n  domain: '\u003cAUTH0_DOMAIN\u003e'\n  clientId: '\u003cAUTH0_CLIENT_ID\u003e',\n  clientSecret: '\u003cAUTH0_CLIENT_SECRET\u003e',\n  audience: 'https://api.mycompany.com/',\n  scope: 'openid profile',\n  redirectUri: 'http://localhost:3000/api/callback',\n  postLogoutRedirectUri: 'http://localhost:3000/',\n  session: {\n    cookieSecret: '\u003cRANDOMLY_GENERATED_SECRET\u003e',\n    cookieLifetime: 60 * 60 * 8,\n    cookieDomain: 'https://mycompany.com',\n    storeAccessToken: true\n  }\n});\n```\n\nThen you could create a route (eg: `/pages/api/customers.js`) which can call an external API (eg: `https://api.mycompany.com`) using the user's `access_token`.\n\n```js\nimport auth0 from \"../../utils/auth0\";\n\nexport default async function getCustomers(req, res) {\n  try {\n    const { accessToken } = await auth0.getSession(req);\n\n    const apiClient = new MyApiClient(accessToken);\n    return apiClient.getCustomers();\n  } catch (error) {\n    console.error(error);\n    res.status(error.status || 500).end(error.message);\n  }\n}\n```\n\n### Requiring Authentication\n\nIf you have API routes for which you want to require the user to be authenticated you can use the `requireAuthentication` handler:\n\n```js\nimport auth0 from \"../../lib/auth0\";\n\nexport default auth0.requireAuthentication(async function billingInfo(\n  req,\n  res\n) {\n  const { user } = await auth0.getSession(req);\n  res.json({\n    email: user.email,\n    country: \"United States\",\n    paymentMethod: \"Paypal\"\n  });\n});\n```\n\nIf the user is authenticated then your API route will simply execute, but if the user is not authenticated an error (401) will be returned:\n\n```json\n{\n  \"error\": \"not_authenticated\",\n  \"description\": \"The user does not have an active session or is not authenticated\"\n}\n```\n\n## Documentation\n\n### Cookies\n\nAll cookies will be set as `HttpOnly, SameSite=Lax` cookies and will be forced to HTTPS (`Secure`) if the application is running with `NODE_ENV=production` and not running on localhost.\n\nThe `HttpOnly` setting will make sure that client-side javascript is unabled to access the cookie to reduce the attack surface of XSS attacks while `SameSite=Lax` will help mitigate CSRF attacks. Read more about SameSite [here](https://auth0.com/blog/browser-behavior-changes-what-developers-need-to-know/).\n\n## Troubleshooting\n\n### Error `id_token issued in the future, now 1570650460, iat 1570650461`\n\nIncrease the clock tolerance for id_token validation:\n\n```js\nimport { initAuth0 } from '@auth0/nextjs-auth0';\n\nexport default initAuth0({\n  ...\n  session: {\n    ...\n  },\n  oidcClient: {\n    // Eg: increase the tolerance to 10 seconds.\n    clockTolerance: 10000\n  }\n});\n```\n\n## Contributing\n\nRun NPM install first to install the dependencies of this project:\n\n```bash\nnpm install\n```\n\nIn order to build a release you can run the following commands and the output will be stored in the `dist` folder:\n\n```bash\nnpm run clean\nnpm run lint\nnpm run build\n```\n\nAdditionally you can also run tests:\n\n```bash\nnpm run test\nnpm run test:watch\n```\n\n## Support + Feedback\n\nThis SDK is in Early Access and support is best effort. Open an issue in this repository to get help or provide feedback.\n\n## Vulnerability Reporting\n\nPlease do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/whitehat) details the procedure for disclosing security issues.\n\n## What is Auth0?\n\nAuth0 helps you to easily:\n\n- implement authentication with multiple identity providers, including social (e.g., Google, Facebook, Microsoft, LinkedIn, GitHub, Twitter, etc), or enterprise (e.g., Windows Azure AD, Google Apps, Active Directory, ADFS, SAML, etc.)\n- log in users with username/password databases, passwordless, or multi-factor authentication\n- link multiple user accounts together\n- generate signed JSON Web Tokens to authorize your API calls and flow the user identity securely\n- access demographics and analytics detailing how, when, and where users are logging in\n- enrich user profiles from other data sources using customizable JavaScript rules\n\n[Why Auth0?](https://auth0.com/why-auth0)\n\n## License\n\nThis project is licensed under the MIT license. See the [LICENSE](https://github.com/auth0/nextjs-auth0/blob/master/LICENSE) file for more info.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpoupryc%2Fauthomatic","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpoupryc%2Fauthomatic","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpoupryc%2Fauthomatic/lists"}