From 22eeeff8ec0af360a5061a0a06a7f1ff117fa3f9 Mon Sep 17 00:00:00 2001 From: Zoey Kaiser Date: Mon, 13 Nov 2023 13:37:23 +0100 Subject: [PATCH] replaced main docs to 0.6 docs --- docs/content/1.getting-started/1.index.md | 119 ++++-- .../1.getting-started/2.installation.md | 14 +- .../1.getting-started/3.quick-start.md | 82 +++- .../1.getting-started/4.getting-help.md | 10 +- docs/content/2.configuration/1.index.md | 12 +- docs/content/2.configuration/2.nuxt-config.md | 365 +++++++++++++++--- .../2.configuration/3.nuxt-auth-handler.md | 18 +- docs/content/3.application-side/1.index.md | 11 +- .../2.session-access-and-management.md | 196 +++++++++- .../3.custom-sign-in-page.md | 81 +++- .../3.application-side/4.protecting-pages.md | 25 +- .../3.application-side/5.guest-mode.md | 13 +- docs/content/4.server-side/1.index.md | 10 +- .../2.session-access-and-route-protection.md | 6 +- docs/content/4.server-side/3.jwt-access.md | 4 + docs/content/4.server-side/4.rest-api.md | 9 +- docs/content/5.recipes/1.index.md | 2 +- docs/content/5.recipes/2.strapi.md | 8 +- docs/content/5.recipes/3.directus.md | 4 +- .../5.recipes/4.custom-session-data.md | 14 +- docs/content/5.recipes/5.nuxt-auth-example.md | 2 +- docs/content/5.recipes/6.laravel-passport.md | 12 +- docs/content/5.recipes/7.vercel-deployment.md | 4 +- .../content/{v0.6 => }/6.resources/0.index.md | 0 .../1.external-blogs-guides-examples.md | 4 +- docs/content/6.resources/2.glossary.md | 5 +- docs/content/6.resources/5.errors.md | 4 +- .../{v0.6 => }/6.resources/6.nuxt-security | 0 .../content/v0.5/1.getting-started/1.index.md | 90 +++++ .../v0.5/1.getting-started/2.installation.md | 38 ++ .../v0.5/1.getting-started/3.quick-start.md | 59 +++ .../1.getting-started/4.getting-help.md | 10 +- .../{v0.6 => v0.5}/1.getting-started/_dir.yml | 0 docs/content/v0.5/2.configuration/1.index.md | 17 + .../v0.5/2.configuration/2.nuxt-config.md | 84 ++++ .../2.configuration/3.nuxt-auth-handler.md | 18 +- .../{v0.6 => v0.5}/2.configuration/_dir.yml | 0 .../3.application-side/1.index.md | 11 +- .../2.session-access-and-management.md | 92 +++++ .../3.custom-sign-in-page.md | 81 +--- .../3.application-side/4.protecting-pages.md | 25 +- .../3.application-side/5.guest-mode.md | 13 +- .../3.application-side/_dir.yml | 0 docs/content/v0.5/4.server-side/1.index.md | 14 + .../2.session-access-and-route-protection.md | 6 +- .../4.server-side/3.jwt-access.md | 4 - .../4.server-side/4.rest-api.md | 9 +- .../{v0.6 => v0.5}/4.server-side/_dir.yml | 0 .../{v0.6 => v0.5}/5.recipes/1.index.md | 2 +- .../{v0.6 => v0.5}/5.recipes/2.strapi.md | 8 +- .../{v0.6 => v0.5}/5.recipes/3.directus.md | 4 +- .../5.recipes/4.custom-session-data.md | 14 +- .../5.recipes/5.nuxt-auth-example.md | 2 +- .../5.recipes/6.laravel-passport.md | 12 +- .../5.recipes/7.vercel-deployment.md | 4 +- .../5.recipes/8.azure-ad-example.md | 0 .../content/{v0.6 => v0.5}/5.recipes/_dir.yml | 0 docs/content/{ => v0.5}/6.resources/0.index | 0 .../1.external-blogs-guides-examples.md | 4 +- .../{v0.6 => v0.5}/6.resources/2.glossary.md | 5 +- .../{v0.6 => v0.5}/6.resources/3.security.md | 0 .../6.resources/4.prior-work.md | 0 .../{v0.6 => v0.5}/6.resources/5.errors.md | 4 +- .../{v0.6 => v0.5}/6.resources/_dir.yml | 0 docs/content/{v0.6 => v0.5}/_dir.yml | 2 +- .../content/v0.6/1.getting-started/1.index.md | 147 ------- .../v0.6/1.getting-started/2.installation.md | 48 --- .../v0.6/1.getting-started/3.quick-start.md | 123 ------ docs/content/v0.6/2.configuration/1.index.md | 11 - .../v0.6/2.configuration/2.nuxt-config.md | 331 ---------------- .../2.session-access-and-management.md | 248 ------------ docs/content/v0.6/4.server-side/1.index.md | 14 - 72 files changed, 1294 insertions(+), 1294 deletions(-) rename docs/content/{v0.6 => }/6.resources/0.index.md (100%) rename docs/content/{v0.6 => }/6.resources/6.nuxt-security (100%) create mode 100644 docs/content/v0.5/1.getting-started/1.index.md create mode 100644 docs/content/v0.5/1.getting-started/2.installation.md create mode 100644 docs/content/v0.5/1.getting-started/3.quick-start.md rename docs/content/{v0.6 => v0.5}/1.getting-started/4.getting-help.md (51%) rename docs/content/{v0.6 => v0.5}/1.getting-started/_dir.yml (100%) create mode 100644 docs/content/v0.5/2.configuration/1.index.md create mode 100644 docs/content/v0.5/2.configuration/2.nuxt-config.md rename docs/content/{v0.6 => v0.5}/2.configuration/3.nuxt-auth-handler.md (83%) rename docs/content/{v0.6 => v0.5}/2.configuration/_dir.yml (100%) rename docs/content/{v0.6 => v0.5}/3.application-side/1.index.md (62%) create mode 100644 docs/content/v0.5/3.application-side/2.session-access-and-management.md rename docs/content/{v0.6 => v0.5}/3.application-side/3.custom-sign-in-page.md (54%) rename docs/content/{v0.6 => v0.5}/3.application-side/4.protecting-pages.md (86%) rename docs/content/{v0.6 => v0.5}/3.application-side/5.guest-mode.md (84%) rename docs/content/{v0.6 => v0.5}/3.application-side/_dir.yml (100%) create mode 100644 docs/content/v0.5/4.server-side/1.index.md rename docs/content/{v0.6 => v0.5}/4.server-side/2.session-access-and-route-protection.md (76%) rename docs/content/{v0.6 => v0.5}/4.server-side/3.jwt-access.md (95%) rename docs/content/{v0.6 => v0.5}/4.server-side/4.rest-api.md (85%) rename docs/content/{v0.6 => v0.5}/4.server-side/_dir.yml (100%) rename docs/content/{v0.6 => v0.5}/5.recipes/1.index.md (89%) rename docs/content/{v0.6 => v0.5}/5.recipes/2.strapi.md (84%) rename docs/content/{v0.6 => v0.5}/5.recipes/3.directus.md (98%) rename docs/content/{v0.6 => v0.5}/5.recipes/4.custom-session-data.md (93%) rename docs/content/{v0.6 => v0.5}/5.recipes/5.nuxt-auth-example.md (83%) rename docs/content/{v0.6 => v0.5}/5.recipes/6.laravel-passport.md (95%) rename docs/content/{v0.6 => v0.5}/5.recipes/7.vercel-deployment.md (95%) rename docs/content/{ => v0.5}/5.recipes/8.azure-ad-example.md (100%) rename docs/content/{v0.6 => v0.5}/5.recipes/_dir.yml (100%) rename docs/content/{ => v0.5}/6.resources/0.index (100%) rename docs/content/{v0.6 => v0.5}/6.resources/1.external-blogs-guides-examples.md (91%) rename docs/content/{v0.6 => v0.5}/6.resources/2.glossary.md (77%) rename docs/content/{v0.6 => v0.5}/6.resources/3.security.md (100%) rename docs/content/{v0.6 => v0.5}/6.resources/4.prior-work.md (100%) rename docs/content/{v0.6 => v0.5}/6.resources/5.errors.md (96%) rename docs/content/{v0.6 => v0.5}/6.resources/_dir.yml (100%) rename docs/content/{v0.6 => v0.5}/_dir.yml (75%) delete mode 100644 docs/content/v0.6/1.getting-started/1.index.md delete mode 100644 docs/content/v0.6/1.getting-started/2.installation.md delete mode 100644 docs/content/v0.6/1.getting-started/3.quick-start.md delete mode 100644 docs/content/v0.6/2.configuration/1.index.md delete mode 100644 docs/content/v0.6/2.configuration/2.nuxt-config.md delete mode 100644 docs/content/v0.6/3.application-side/2.session-access-and-management.md delete mode 100644 docs/content/v0.6/4.server-side/1.index.md diff --git a/docs/content/1.getting-started/1.index.md b/docs/content/1.getting-started/1.index.md index 77825ba4..92623391 100644 --- a/docs/content/1.getting-started/1.index.md +++ b/docs/content/1.getting-started/1.index.md @@ -1,54 +1,112 @@ --- -description: "Introduction to `nuxt-auth` and its features as an authentication module for your Vue / Nuxt 3 application." +description: "Introduction to `nuxt-auth` and its features as an authentication module for your Vue / Nuxt 3 application: authentication for static- and non-static Nuxt 3 applications." --- # Introduction ::alert{type="info"} -[Checkout the `0.6`-docs](/nuxt-auth/v0.6/getting-started) if you want to get get started with the `local`-provider or have a static Nuxt application. +These are the docs for the experimental v0.6 version of `nuxt-auth` with static Nuxt 3 and `local` provider support. [Checkout the `0.5`-docs](/nuxt-auth/getting-started) for the nuxt-auth-version <=0.5. :: -`nuxt-auth` is an open source Nuxt module that provides authentication for non-static Nuxt 3 applications. +`nuxt-auth` is an open source Nuxt module that provides authentication for Nuxt 3 applications. -The easiest way to get started with `nuxt-auth` is using [the sidebase Merino stack](/sidebase): -::code-group -```bash [npm] -npm create sidebase@latest -``` -```bash [pnpm] -pnpm create sidebase@latest -``` -```bash [yarn] -# Note: Due to a known problem with `yarn`, it is not possible to force yarn to always use `@latest`: https://github.com/yarnpkg/yarn/issues/6587 -yarn create sidebase -``` +`nuxt-auth` supports the following: +::list{type="success"} +- `useAuth` composable to perform authentication-related actions from the application +- global- and local-application middleware to protect application-pages +- guest-mode to only allows guest to see certain pages (e.g.: the login page) +- authentication-backend setup for the `authjs`-auth-provider +- static Nuxt 3 apps with the `local`-auth-provider +- documentation, recipes and example code to get you started :: -This will create a Nuxt 3 project with `nuxt-auth` already setup & working. -`nuxt-auth` supports three main types of authentication out of the box: +`nuxt-auth` employs 2 providers to facilitate the act of authenticating a user: ::list{type="success"} -- OAuth: Authentication via third-party OAuth providers like Google, Azure, Github, Discord, ... -- Credentials: Authentication via a username and password that the user supplies and custom logic that you implement yourself -- Emails: Authentication via "Magic URL" emails, like Slack or Notion +- `local`: Username and password authentication. `local` expects the endpoint to return a token that can be used to authenticate subsequent requests +- `authjs`: A `authjs` (`next-auth`) based provider that supports most OAuth- and Magic-URL sign-ins (think Slack or Notion). This provider also supports username and password based sign-in, but discourages from using it :: -`nuxt-auth` is able to provide the above and more (like database adapters, callback hooks, ...) by wrapping [NextAuth.js](https://github.com/nextauthjs/next-auth) under the hood. This gives the reliability & convenience of a >12.000 github star library to the Nuxt 3 ecosystem with a native nuxt developer experience (DX). Wrapping `NextAuth.js` has the second advantage that many OAuth providers, database adapters, callbacks and more are supported out-of-the-box. This means that whenever you want to achieve something within the `NuxtAuthHandler` you can use all NextAuth guides and documentation to do so - the authentication handlers behave identical. - -`nuxt-auth` also provides Nuxt 3 specific features like a convenient application-side composable to login, logout, access user-authentication data or an authentication middleware and plugin that take care of managing the user authentication lifecycle by fetching authentication data on initial load, refreshing the user authentication on re-focusing the tab and more. +Other libraries / modules would call these authentication-schemes, backends or maybe even strategys. ::callout #summary Show me the code! #content -Visit the [quick start](/nuxt-auth/getting-started/quick-start) page to see code examples. +Visit the [quick start](/nuxt-auth/v0.6/getting-started/quick-start) page to see code examples. Checkout the example `nuxt-auth` app: https://nuxt-auth-example.sidebase.io/ Here's the source-code https://github.com/sidebase/nuxt-auth-example of the example app. :: -## Authentication providers +## Which Provider should I pick? + +To pick a provider you will first have to take into consideration the requirements of your use-case. Below is a small table to help you pick: + +| | authjs | local | +|----------------------------------------------------------- |-------------------------------------: |------: | +| **Authentication Methods** | | | +| OAuth | ✅ (>50 providers) | ❌ | +| Magic URLs | ✅ | ❌ | +| Credential / Username + Password flow | 🚧 (if possible: use `local` instead) | ✅ | +| | | | +| **Features** | | | +| app `useAuth`-composable to sign-in, sign-out, ... | ✅ | ✅ | +| session-management: auto-refresh, refresh on refocus, ... | ✅ | ✅ | +| static apps ("nuxi generate") | ❌ | ✅ | +| guest mode | ✅ | ✅ | +| app-side middleware | ✅ | ✅ | +| server-side middleware | ✅ | ✅ | +| pre-made login-page | ✅ (impacts bundle-size) | ❌ | +| database-adapters, server-side callback-hooks | ✅ | ❌ | + +In general one can say that picking: +- `authjs` is best suited for plug-and-play OAuth for established oauth-providers or magic-url based sign-ins +- `local` is best when you already have a backend that accepts username + password as a login or want to build a static application + +### `authjs` Remarks + +The `authjs` provider is able to provide all of its features by wrapping [Auth.js / NextAuth.js](https://github.com/nextauthjs/next-auth) under the hood. This gives the reliability & convenience of a >12.000 github star library to the Nuxt 3 ecosystem with a native nuxt developer experience (DX). Wrapping `Auth.js / NextAuth.js` has the second advantage that many OAuth providers, database adapters, callbacks and more are supported out-of-the-box. This also means that you can use all NextAuth.js and Auth.js guides and documentation to achieve things with the `authjs` provider of `nuxt-auth`. + +`nuxt-auth` also provides Nuxt 3 specific features like a convenient application-side composable to login, logout, access user-authentication data or an authentication middleware and plugin that take care of managing the user authentication lifecycle by fetching authentication data on initial load, refreshing the user authentication on re-focusing the tab and more. + +In the future a separate OAuth provider for static apps may be added, read the next section for more on this. + +#### Auth.js vs next-auth + +We use `authjs` everywhere to mean `authjs` and `next-auth` interchangably as `next-auth` is currently transitioning to become `authjs` (branded name: `Auth.js`), see [the announcement here](https://twitter.com/balazsorban44/status/1603082914362986496). + +We are following this transition and are changing code related to this as it becomes stable enough to use it. You can follow our implementation of this transition [in this issue](https://github.com/sidebase/nuxt-auth/v0.6/issues/117). If you are googling anything related to this provider, we recommend that you still use the term `next-auth` as this is still the mainly used library and the stable one we mostly use under the hood. New features that are `Auth.js` only are _not_ guaranteed to work at the moment, as we still mostly rely on next-auth as a stable foundation. + +### `local` Remarks + +The `local` provider is based on [the local schema of the Nuxt 2 nuxt-auth module](https://auth.nuxtjs.org/schemes/local). It was added in v0.6.0 of `nuxt-auth` and serves as a starting point to add further static providers like [cookie based](https://auth.nuxtjs.org/schemes/cookie) authentication, support for [refresh tokens](https://auth.nuxtjs.org/schemes/refresh) and [static OAuth support](https://auth.nuxtjs.org/schemes/oauth2). + +The `local` provider works by receiving an authentication token from the backend it send a `username` and `password` to. This could for example be a JWT token. The `local` provider then stores this token and makes it accessible to you for use. The `local` provider will also fetch user / session information from the backend once it has successfully logged in. + +Any help with this effort is very welcome! Feel free to open an issue or a PR to add support for further providers 💘. + +## Starting with sidebase + +The easiest way to get started with `nuxt-auth` is using [the sidebase Merino stack](/sidebase): +::code-group +```bash [npm] +npm create sidebase@latest +``` +```bash [pnpm] +pnpm create sidebase@latest +``` +```bash [yarn] +# Note: Due to a known problem with `yarn`, it is not possible to force yarn to always use `@latest`: https://github.com/yarnpkg/yarn/issues/6587 +yarn create sidebase +``` +:: +This will create a Nuxt 3 project with `nuxt-auth` already setup & working. + +## Feature Collection + +### Authentication providers ::list{type="success"} - OAuth (e.g., Github, Google, Twitter, Azure, ...) @@ -57,26 +115,25 @@ Here's the source-code https://github.com/sidebase/nuxt-auth-example of the exam - Email Magic URLs :: -## Application Side Session Management -::alert{type="info"} -Prior to v0.5.0 `useAuth()` was called `useSession()`. -:: +### Application Side Session Management + ::list{type="success"} - composable `const { signIn, signOut, status, data, lastRefreshedAt, ... } = useAuth()` - Auto-refresh the session periodically - Auto-refresh the session on tab-refocus - Efficient session fetching: One time on page load, afterwards for specific actions (e.g., on navigation) - Full typescript support for all methods and properties +- Guest-Mode :: -## Application Protection +### Application Protection ::list{type="success"} - Application-side middleware protection either for the full application or specific pages - Server-side middleware and endpoint protection :: -## REST API +### REST API (authjs only) ::list{type="success"} - `GET /signin`, diff --git a/docs/content/1.getting-started/2.installation.md b/docs/content/1.getting-started/2.installation.md index bcc2186d..70a28930 100644 --- a/docs/content/1.getting-started/2.installation.md +++ b/docs/content/1.getting-started/2.installation.md @@ -18,10 +18,12 @@ pnpm i -D @sidebase/nuxt-auth :: ::alert{type="info"} -Note that we try our best to keep `nuxt-auth` stable, but it is also a young module that is in active development. If you want to be extra sure nothing breaks, you should pin the patch version, e.g., by using `--save-exact` when running the install command. +Note that we try our best to keep `nuxt-auth` stable, but it is also a fresh module that is in active development. If you want to be extra sure nothing breaks, you should pin the patch version, e.g., by using `--save-exact` when running the install command. :: -`nuxt-auth` has `next-auth` as a peer-dependency. With all package managers except `npm` you must install the peer dependency alongside `nuxt-auth`: +## Specifics: `authjs`-Provider + +If you want to use the `authjs` provider, you have to install `next-auth`. With all package managers except `npm` you must manually install the peer dependency alongside `nuxt-auth`: ::code-group ```bash [yarn] yarn add next-auth@4.21.1 @@ -33,6 +35,14 @@ pnpm i next-auth@4.21.1 You can find all available `next-auth` versions [on npm](https://www.npmjs.com/package/next-auth?activeTab=versions). You do not need to install any other peer-dependencies in order to use `nuxt-auth`. +If you are unsure which provider to choose, have a look at the [overview on the getting-started page](/nuxt-auth/v0.6/getting-started#which-provider-should-i-pick). + +## Specifics: `local`-Provider + +The `local` provider does not have any specific extra dependencies. However, you will need to make sure that you have a backend somewhere that provides username + password based authentication, [read more about this on the quick-start page](/nuxt-auth/v0.6/getting-started/quick-start). + +If you are unsure which provider to choose, have a look at the [overview on the getting-started page](/nuxt-auth/v0.6/getting-started#which-provider-should-i-pick). + ## Requirements `nuxt-auth` only needs Nuxt 3 to run. In the future Nuxt 2 or Nuxt Bridge may be supported. diff --git a/docs/content/1.getting-started/3.quick-start.md b/docs/content/1.getting-started/3.quick-start.md index ec8ae56a..e2be91f0 100644 --- a/docs/content/1.getting-started/3.quick-start.md +++ b/docs/content/1.getting-started/3.quick-start.md @@ -1,14 +1,36 @@ # Quick Start -After [installing the package](/nuxt-auth/getting-started/installation), add the package to your `nuxt.config.ts`: - -```ts +After [following the installation-steps](/nuxt-auth/v0.6/getting-started/installation), add `@sidebase/nuxt-auth` to your `nuxt.config.ts` and specify the provider-type you want to use: +::code-group +```ts [authjs] export default defineNuxtConfig({ - modules: ['@sidebase/nuxt-auth'], + modules: ['@sidebase/nuxt-auth'], + auth: { + provider: { + type: 'authjs' + } + } }) ``` +```ts [local] +export default defineNuxtConfig({ + modules: ['@sidebase/nuxt-auth'], + auth: { + provider: { + type: 'local' + } + } +}) +``` +:: -Then create the authentication handler (`NuxtAuthHandler`) that will expose the API endpoints for handling all authentication-related requests and add at least one [authentication provider](https://next-auth.js.org/providers/): +Then continue with the provider-specific steps below. + +## Provider-specific Steps + +### Provider: `authjs` + +After the `nuxt.config.ts` setup from above you have to create the authentication handler (`NuxtAuthHandler`) that will setup the backend and expose the API endpoints for handling all authentication-related requests and add at least one [authentication provider](https://next-auth.js.org/providers/): ```ts // file: ~/server/api/auth/[...].ts @@ -26,11 +48,53 @@ export default NuxtAuthHandler({ }) ``` -That's it! You can now use all user-related functionality, for example: +### Provider: `local` + +The local provider does not require any additional steps, as it relies on an already existing backend. By default, the `local` provider will try to reach this backend using the following default-configuration: +```ts +{ + baseURL: '/api/auth', + endpoints: { + signIn: { path: '/login', method: 'post' }, + signOut: { path: '/logout', method: 'post' }, + signUp: { path: '/register', method: 'post' }, + getSession: { path: '/session', method: 'get' } + } +} +``` + +So when you call the `signIn` method, the endpoint `/api/auth/login` will be hit with the `username` and `password` you pass as a body-payload. You likely have to modify these parameters to fit to your backend - you can adjust these parameters in your `nuxt.config.ts` using the options [specified here](/nuxt-auth/v0.6/configuration/nuxt-config). + +Note: The backend can also be in the same Nuxt 3 application, e.g., have a look at this example in the `nuxt-auth` repository: +- [full nuxt app](https://github.com/sidebase/nuxt-auth/tree/main/playground-local) + - its [backend](https://github.com/sidebase/nuxt-auth/tree/main/playground-local/server/api/auth) + - its [`nuxt.config.ts`](https://github.com/sidebase/nuxt-auth/blob/main/playground-local/nuxt.config.ts) ::alert{type="info"} -Prior to v0.5.0 `useAuth()` was called `useSession()`. +The linked example-implementation only serves as a starting-point and is not considered to be secure. :: + +The backend musst accept a request with a body like: +```ts +{ + username: 'bernd@sidebase.io', + password: 'hunter2' +} +``` + +and return a token that can be used to authenticate future requests in the response body, e.g., like: +```ts +{ + tokens: { + accessToken: 'eyBlaBlub' + } +} +``` + +## Finishing up + +That's it! You can now use all user-related functionality, for example: + ::code-group ```ts [Application side] // file: e.g ~/pages/login.vue @@ -42,7 +106,7 @@ data.value // Session data, e.g., expiration, user.email, ... await signIn() // Sign in the user await signOut() // Sign out the user ``` -```ts [Server side] +```ts [authjs: Server side] // file: e.g: ~/server/api/session.get.ts import { getServerSession } from '#auth' @@ -56,4 +120,4 @@ export default eventHandler(async (event) => { ``` :: -To learn how to protect pages read [about the application-side usage](/nuxt-auth/application-side), to learn how to protect server-routes and API endpoints read [about the server-side usage](/nuxt-auth/server-side). +To learn how to protect pages read [about the application-side usage](/nuxt-auth/v0.6/application-side), to learn how to protect server-routes and API endpoints read [about the server-side usage](/nuxt-auth/v0.6/server-side). You can also find more provider-specific information on these pages. diff --git a/docs/content/1.getting-started/4.getting-help.md b/docs/content/1.getting-started/4.getting-help.md index aa03b4ec..43afd3a9 100644 --- a/docs/content/1.getting-started/4.getting-help.md +++ b/docs/content/1.getting-started/4.getting-help.md @@ -8,8 +8,14 @@ At some point, you may find that there's an issue you need some help with. But don't worry! We're a friendly community of developers and we'd love to help. Concretely this means to: - Checkout the docs (page that you are currently viewing), -- Search open issues and discussions: https://github.com/sidebase/nuxt-auth/issues +- Search open & resolved issues and discussions: https://github.com/sidebase/nuxt-auth/v0.6/issues - Hop on Discord to ask us directly: https://discord.gg/VzABbVsqAc, -- Open an issue to file a bug, ask for an enhancement or get an answer to a question: https://github.com/sidebase/nuxt-auth/issues/new/choose +- Open an issue to file a bug, ask for an enhancement or get an answer to a question: https://github.com/sidebase/nuxt-auth/v0.6/issues/new/choose We aim to follow the getting-help standards of the nuxt-project as described here and ask you to do the same when opening an issue or pinging us for help: https://nuxt.com/docs/community/getting-help#getting-help. + +## Minimal Reproductions + +When resolving a bug a minimal reproduction is almost always required, [read on the official nuxt.com page how to create one](https://nuxt.com/docs/community/reporting-bugs#create-a-minimal-reproduction). + +Note that your reproduction should also work outside of providers like stackblitz. The reason for this is that stackblitz (and likely other, similar providers) do not properly support cookies, which are essential for `nuxt-auth` to work. diff --git a/docs/content/2.configuration/1.index.md b/docs/content/2.configuration/1.index.md index 277fd946..b8b8343c 100644 --- a/docs/content/2.configuration/1.index.md +++ b/docs/content/2.configuration/1.index.md @@ -4,14 +4,8 @@ description: "Overview of the configuration options of `nuxt-auth` for Vue / Nux # Overview -There's two places to configure `nuxt-auth`: -- [auth key in `nuxt.config.ts`](/nuxt-auth/configuration/nuxt-config): Configure the module itself, e.g., whether global page protection is enabled -- [NuxtAuthHandler](/nuxt-auth/configuration/nuxt-auth-handler): Configure the authentication behavior, e.g., what authentication providers to use - -For development, using the [Quick Start configuration](/nuxt-auth/getting-started/quick-start) will already bring you quite far. For a production deployment, you will have to: -- set the `origin` by: - 1. exporting the `AUTH_ORIGIN`-environment variable _at runtime_ (higher precedence) - 2. setting the `origin`-key inside the `nuxt.config.ts` config _at build-time_ (lower precendence) -- set a secret inside the `NuxtAuthHandler` config +Use the following places to configure how `nuxt-auth` behaves: +- `local` & `authjs`-provider: The [auth key in `nuxt.config.ts`](/nuxt-auth/v0.6/configuration/nuxt-config). Use it to configure the module itself, e.g., whether global page protection is enabled +- `authjs`-provider: The [NuxtAuthHandler](/nuxt-auth/v0.6/configuration/nuxt-auth-handler). Use it to configure the `authjs` authentication behavior, e.g., what authentication providers to use. See the detailed possible configuration options on the next pages. diff --git a/docs/content/2.configuration/2.nuxt-config.md b/docs/content/2.configuration/2.nuxt-config.md index e7d6d9fb..242b26ac 100644 --- a/docs/content/2.configuration/2.nuxt-config.md +++ b/docs/content/2.configuration/2.nuxt-config.md @@ -5,80 +5,327 @@ toc: true # Module (nuxt.config.ts) -Use the `auth`-key inside the `nuxt.config.ts` to configure the `nuxt-auth` module itself. Here are the available configuration options and their default values: -```ts -export default defineNuxtConfig({ - modules: ['@sidebase/nuxt-auth'], - auth: { - // The module is enabled. Change this to disable the module - isEnabled: true, - - // The origin is set to the development origin. Change this when deploying to production by setting `origin` in this config before build-time or by exporting `AUTH_ORIGIN` by running `export AUTH_ORIGIN=...` - origin: 'http://localhost:3000', - - // The base path to the authentication endpoints. Change this if you want to add your auth-endpoints at a non-default location - basePath: '/api/auth', - - // Whether to periodically refresh the session. Change this to `true` for a refresh every seconds or set this to a number like `5000` for a refresh every 5000 milliseconds (aka: 5 seconds) - enableSessionRefreshPeriodically: false, - - // Whether to refresh the session whenever a window focus event happens, i.e, when your user refocuses the window. Set this to `false` to turn this off - enableSessionRefreshOnWindowFocus: true, - - // Whether to add a global authentication middleware that will protect all pages without exclusion - globalAppMiddleware: false, - - // Select the default-provider to use when `signIn` is called. Setting this here will also effect the global middleware behavior: E.g., when you set it to `github` and the user is unauthorized, they will be directly forwarded to the Github OAuth page instead of seeing the app-login page - defaultProvider: undefined, - - // Whether to automatically set the callback url to the page the user tried to visit when the middleware stopped them. This is useful to disable this when using the credentials provider, as it does not allow a `callbackUrl`. Setting this to a string-value will result in that being used as the callbackUrl path. - addDefaultCallbackUrl: true, - - - // Configuration of the global auth-middleware (only applies if you set `globalAppMiddleware: true` above!) - globalMiddlewareOptions: { - - // Whether to allow access to 404 pages without authentication. Set this to `false` to force users to sign-in before seeing `404` pages. Setting this to false may lead to vue-router problems (as the target page does not exist) - allow404WithoutAuth: true, - - // Whether to automatically set the callback url to the page the user tried to visit when the middleware stopped them. This is useful to disable this when using the credentials provider, as it does not allow a `callbackUrl`. Setting this to a string-value will result in that being used as the callbackUrl path. Note: You also need to set the global `addDefaultCallbackUrl` setting to `false` if you want to fully disable this for the global middleware. - addDefaultCallbackUrl: true - } - } -}) +Use the `auth`-key inside the `nuxt.config.ts` to configure the `nuxt-auth` module itself. The module config has a root-config and then sub-properties for different aspects of the module: +::code-group +```ts [root] +/** + * Configuration for the whole module. + */ +interface ModuleOptions { + /** + * Whether the module is enabled at all + */ + isEnabled?: boolean + /** + * Full url at which the app will run combined with the path to authentication. You can set this differently depending on your selected authentication-provider: + * - `authjs`: You must set the full URL, with origin and path in production. You can leave this empty in development + * - `local`: You can set a full URL, but can also leave this empty to fallback to the default value of `/api/auth` or set only the path. + * + * ### `authjs` + * + * `baseURL` can be `undefined` during development but _must_ be set to the combination of origin + path that points to your `NuxtAuthHandler` for production. The origin consists out of: + * - `scheme`: http / https + * - `host`: e.g., localhost, example.org, google.com + * - `port`: _empty_ (implies `:80` for http and `:443` for https), :3000, :8888 + * + * The path then is a string like `/path/to/auth/api/endpoint/root`. + * + * ### `local` + * + * Defaults to `/api/auth` for both development and production. Setting this is optional, if you set it you can set it to either: + * - just a path: Will lead to `nuxt-auth` using `baseURL` as a relative path appended to the origin you deploy to. Example: `/backend/auth` + * - an origin and a path: Will leav to `nuxt-auth` using `baseURL` as an absolute request path to perform requests to. Example: `https://example.com/auth` + * + * Note: If you point to a different origin than the one you deploy to you likely have to take care of CORS: Allowing cross origin requests. + * + * @example undefined + * @example http://localhost:3000 + * @example https://example.org/_auth + * @example https://my-cool-site.com/api/authentication + * @default http://localhost:3000/api/auth Default for `authjs` provider in development + * @default undefined Default for `authjs` in production, will result in an error + * @default /api/auth Default for `local` for both production and development + */ + baseURL?: string + /** + * Configuration of the authentication provider. Different providers are supported: + * - auth.js: OAuth focused provider for non-static Nuxt 3 applications + * - local: Provider for credentials & token based backends, e.g., written by yourself or provided by something like Laraval + * + * Find more about supported providers here: https://sidebase.io/nuxt-auth/v0.6/getting-started + * + */ + provider?: AuthProviders + /** + * Configuration of the application-side session. + */ + session?: SessionConfig + /** + * Whether to add a global authentication middleware that protects all pages. Can be either `false` to disable, `true` to enabled + * or an object to enable and apply extended configuration. + * + * If you enable this, everything is going to be protected and you can selectively disable protection for some pages by specifying `definePageMeta({ auth: false })` + * If you disable this, everything is going to be public and you can selectively enable protection for some pages by specifying `definePageMeta({ auth: true })` + * + * Read more on this topic [in the page protection docs](https://sidebase.io/nuxt-auth/v0.6/application-side/protecting-pages#global-middleware). + * + * @example true + * @example { allow404WithoutAuth: true } + * @default false + */ + globalAppMiddleware?: GlobalMiddlewareOptions | boolean +} +``` +```ts [AuthProviders - authjs] +/** + * Configuration for the `authjs`-provider. + */ +type ProviderAuthjs = { + /** + * Uses the `authjs` provider to facilitate autnetication. Currently, two providers exclusive are supported: + * - `authjs`: `next-auth` / `auth.js` based OAuth, Magic URL, Credential provider for non-static applications + * - `local`: Username and password provider with support for static-applications + * + * Read more here: https://sidebase.io/nuxt-auth/v0.6/getting-started + */ + type: Extract + /** + * If set to `true`, `authjs` will use either the `x-forwarded-host` or `host` headers instead of `auth.baseURL`. + * + * Make sure that reading `x-forwarded-host` on your hosting platform can be trusted. + * - ⚠ **This is an advanced option.** Advanced options are passed the same way as basic options, + * but **may have complex implications** or side effects. + * You should **try to avoid using advanced options** unless you are very comfortable using them. + * @default false + */ + trustHost: boolean + /** + * Select the default-provider to use when `signIn` is called. Setting this here will also effect the global middleware behavior: E.g., when you set it to `github` and the user is unauthorized, they will be directly forwarded to the Github OAuth page instead of seeing the app-login page. + * + * @example "github" + * @default undefined + */ + defaultProvider: SupportedProviders | undefined + /** + * Whether to add a callbackUrl to sign in requests. Setting this to a string-value will result in that being used as the callbackUrl path. Setting this to `true` will result in the blocked original target path being chosen (if it can be determined). + */ + addDefaultCallbackUrl: boolean | string +} +``` +```ts [AuthProviders - local] +/** + * Configuration for the `local`-provider. + */ +type ProviderLocal = { + /** + * Uses the `local` provider to facilitate autnetication. Currently, two providers exclusive are supported: + * - `authjs`: `next-auth` / `auth.js` based OAuth, Magic URL, Credential provider for non-static applications + * - `local`: Username and password provider with support for static-applications + * + * Read more here: https://sidebase.io/nuxt-auth/v0.6/getting-started + */ + type: Extract + /** + * Endpoints to use for the different methods. `nuxt-auth` will use this and the root-level `baseURL` to create the final request. E.g.: + * - `baseURL=/api/auth`, `path=/login` will result in a request to `/api/auth/login` + * - `baseURL=http://localhost:5000/_authenticate`, `path=/sign-in` will result in a request to `http://localhost:5000/_authenticate/sign-in` + */ + endpoints?: { + /** + * What method and path to call to perform the sign-in. This endpoint must return a token that can be used to authenticate subsequent requests. + * + * @default { path: '/login', method: 'post' } + */ + signIn?: { path?: string, method?: RouterMethod }, + /** + * What method and path to call to perform the sign-out. + * + * @default { path: '/logout', method: 'post' } + */ + signOut?: { path?: string, method?: RouterMethod }, + /** + * What method and path to call to perform the sign-up. + * + * @default { path: '/register', method: 'post' } + */ + signUp?: { path?: string, method?: RouterMethod }, + /** + * What method and path to call to fetch user / session data from. `nuxt-auth` will send the token received upon sign-in as a header along this request to authenticate. + * + * Refer to the `token` configuration to configure how `nuxt-auth` uses the token in this request. By default it will be send as a bearer-authentication header like so: `Authentication: Bearer eyNDSNJDASNMDSA....` + * + * @default { path: '/session', method: 'get' } + * @example { path: '/user', method: 'get' } + */ + getSession?: { path?: string, method?: RouterMethod }, + }, + /** + * Pages that `nuxt-auth` needs to know the location off for redirects. + */ + pages?: { + /** + * Path of the login-page that the user should be redirected to, when they try to access a protected page without being logged in. This page will also not be blocked by the global middleware. + * + * @default '/login' + */ + login?: string + }, + /** + * Settings for the authentication-token that `nuxt-auth` receives from the `signIn` endpoint and that can be used to authenticate subsequent requests. + */ + token?: { + /** + * How to extract the authentication-token from the sign-in response. + * + * E.g., setting this to `/token/bearer` and returning an object like `{ token: { bearer: 'THE_AUTH_TOKEN' }, timestamp: '2023' }` from the `signIn` endpoint will + * result in `nuxt-auth` extracting and storing `THE_AUTH_TOKEN`. + * + * This follows the JSON Pointer standard, see it's RFC6901 here: https://www.rfc-editor.org/rfc/rfc6901 + * + * @default /token Access the `token` property of the sign-in response object + * @example / Access the root of the sign-in response object, useful when your endpoint returns a plain, non-object string as the token + */ + signInResponseTokenPointer?: string + /** + * Header type to be used in requests. This in combination with `headerName` is used to construct the final authentication-header `nuxt-auth` uses, e.g, for requests via `getSession`. + * + * @default Bearer + * @example Beer + */ + type?: string, + /** + * Header name to be used in requests that need to be authenticated, e.g., to be used in the `getSession` request. + * + * @default Authorization + * @example Auth + */ + headerName?: string, + /** + * Maximum age to store the authentication token for. After the expiry time the token is automatically deleted on the application side, i.e., in the users' browser. + * + * Note: Your backend may reject / expire the token earlier / differently. + * + * @default 1800 + * @example 60 * 60 * 24 + */ + maxAgeInSeconds?: number, + /** + * The cookie sameSite policy. Can be used as a form of csrf forgery protection. If set to `strict`, the cookie will only be passed with requests to the same 'site'. Typically, this includes subdomains. So, a sameSite: strict cookie set by app.mysite.com will be passed to api.mysite.com, but not api.othersite.com. + * + * See the specification here: https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7 + * + * @default 'lax' + * @example 'strict' + */ + sameSiteAttribute?: boolean | 'lax' | 'strict' | 'none' | undefined, + }, + /** + * Define an interface for the session data object that `nuxt-auth` expects to receive from the `getSession` endpoint. + * + * @default { id: 'string | number' } + * @example { id: 'string', name: 'string', email: 'string' } + * @advanced_array_example { id: 'string', email: 'string', name: 'string', role: 'admin | guest | account', subscriptions: "{ id: number, status: 'ACTIVE' | 'INACTIVE' }[]" } + */ + sessionDataType?: SessionDataObject, +} +``` +```ts [SessionConfig] +/** + * Configuration for the application-side session. + */ +type SessionConfig = { + /** + * Whether to refresh the session every `X` milliseconds. Set this to `false` to turn it off. The session will only be refreshed if a session already exists. + * + * Setting this to `true` will refresh the session every second. + * Setting this to `false` will turn off session refresh. + * Setting this to a number `X` will refresh the session every `X` milliseconds. + * + * @example 1000 + * @default false + * + */ + enableRefreshPeriodically: number | boolean + /** + * Whether to refresh the session every time the browser window is refocused. + * + * @example false + * @default true + */ + enableRefreshOnWindowFocus: boolean +} +``` +```ts [GlobalMiddlewareOptions] +/** + * Configuration for the global application-side authentication-middleware. + */ +interface GlobalMiddlewareOptions { + /** + * Whether to add a global authentication middleware that protects all pages. + * + * @example true + * @default false + */ + isEnabled: boolean + /** + * Whether to enforce authentication if the target-route does not exist. Per default the middleware redirects + * to Nuxts' default 404 page instead of forcing a sign-in if the target does not exist. This is to avoid a + * user-experience and developer-experience of having to sign-in only to see a 404 page afterwards. + * + * Note: Setting this to `false` this may lead to `vue-router` + node related warnings like: "Error [ERR_HTTP_HEADERS_SENT] ...", + * this may be related to https://github.com/nuxt/framework/issues/9438. + * + * @example false + * @default true + */ + allow404WithoutAuth?: boolean + /** + * Whether to automatically set the callback url to the page the user tried to visit when the middleware stopped them. This is useful to disable this when using the credentials provider, as it does not allow a `callbackUrl`. Setting this + * to a string-value will result in that being used as the callbackUrl path. Note: You also need to set the global `addDefaultCallbackUrl` setting to `false` if you want to fully disable this. + * + * @example false + * @example /i-caught-you-but-now-you-are-signed-in + * @default true + */ + addDefaultCallbackUrl?: boolean | string +} ``` +:: -The `origin` and the `basePath` together are equivalent to the [`NEXTAUTH_URL` environment variable of NextAuth.js](https://next-auth.js.org/configuration/options#nextauth_url) +## Additional Information -## origin +### Provider `authjs` - baseURL -**You must set the `origin` in production!** You have two options to set it: +**You must set the `baseURL` in production for this provider!** You have two options to set it: 1. Set the `AUTH_ORIGIN` environment variable _at runtime_ -2. Set the `origin` origin-config key inside the `nuxt.config.ts` (see an example above) _at build-time_ +2. Set the `baseURL` baseURL-config key inside the `nuxt.config.ts` (see an example above) _at build-time_ + - Note: Setting this at build time will result in this being hard-backed on the application side if you do not use server-side-rendering + - Note: It's called `baseURL` because it must contain both `origin` and `path` that point to the auth handler, see the long docstring above -The `AUTH_ORIGIN` environment variable takes precendence over the `origin` configuration key, so you can always overwrite the origin at deploy-time. +It is advised to use the `AUTH_ORIGIN` environment variable if possible. The `AUTH_ORIGIN` environment variable takes precendence over the `baseURL` configuration key, so you can always overwrite the origin at deploy-time. -The origin must be set so that `nuxt-auth` can ensure that callbacks for authentication are correct. The `origin` consists out of (up to) 3 parts: +The `baseURL` must be set so that `nuxt-auth` can ensure that callbacks for authentication are correct. Examples of a `baseURL` with both origin and path are: +- `https://example.org/api/auth` +- `http://localhost:2345/_auth` +- `https://app.company.com/api/auth` + +#### Explanation: What is an origin? + +The `origin` consists out of (up to) 3 parts: - scheme: `http` or `https` - host: e.g., `localhost`, `example.org`, `www.sidebase.io` - port: e.g., `:3000`, `:4444`; leave empty to implicitly set `:80` for http, and `:443` for https (this is an internet convention, don't ask) For the demo-app at https://nuxt-auth-example.sidebase.io we set the `origin` to `https://nuxt-auth-example.sidebase.io`. If for some reason required, you can explicitly set the `origin` to `http://localhost:3000` to stop `nuxt-auth` from aborting `npm run build` when the origin is unset. -## basePath +#### Explanation: What is the path? -This is what tells the module where you added the authentication endpoints. Per default the `basePath` is set to `/api/auth`, so that means that the module expects that all requests to `/api/auth/*` will be handled by the `NuxtAuthHandler`. +This is what tells the module where you added the authentication endpoints. By default this documentation recommends to use `/api/auth`, so that means that the module expects that all requests to `/api/auth/*` will be handled by the `NuxtAuthHandler`. -To statify this, you need to create a [catch-all server-route](https://nuxt.com/docs/guide/directory-structure/pages/#catch-all-route) at that location by creating a file `~/server/api/auth/[...].ts` that exports the `NuxtAuthHandler`, see more on this in the [Quick Start](/nuxt-auth/getting-started/quick-start) or in the [`NuxtAuthHandler` documentation](/nuxt-auth/configuration/nuxt-auth-handler) +To statify this, you need to create a [catch-all server-route](https://nuxt.com/docs/guide/directory-structure/pages/#catch-all-route) at that location by creating a file `~/server/api/auth/[...].ts` that exports the `NuxtAuthHandler`, see more on this in the [Quick Start](/nuxt-auth/v0.6/next/getting-started/quick-start) or in the [`NuxtAuthHandler` documentation](/nuxt-auth/v0.6/next/configuration/nuxt-auth-handler) -If you want to have the authentication at another location, you can overwrite the `basePath`, e.g., when setting: -- `basePath: "/api/_auth"` -> add the authentication catch-all endpoints into `~/server/api/_auth/[...].ts` -- `basePath: "/_auth"` -> add the authentication catch-all endpoints into `~/server/routes/_auth/[...].ts` +If you want to have the authentication at another location, you should change the path, e.g., when setting the path-part of the `baseURL` to: +- `path: "/api/_auth"` -> you need to add the authentication catch-all endpoints into `~/server/api/_auth/[...].ts` and this is where `nuxt-auth` will look +- `path: "/_auth"` -> you need to add the authentication catch-all endpoints into `~/server/routes/_auth/[...].ts` and this is where `nuxt-auth` will look See [Nuxt server-routes docs on catch-all routes for a further explanation.](https://nuxt.com/docs/guide/directory-structure/server#server-routes) - -## globalAppMiddleware - -This is a middleware that comes included with `nuxt-auth`. When you enable it, it will protect _all_ pages, so even your index page (`/`) will not be accessible without a login anymore. - -Read more on this topic [in the page protection docs](/nuxt-auth/application-side/protecting-pages#global-middleware). diff --git a/docs/content/2.configuration/3.nuxt-auth-handler.md b/docs/content/2.configuration/3.nuxt-auth-handler.md index 0cd446c9..6cb152b6 100644 --- a/docs/content/2.configuration/3.nuxt-auth-handler.md +++ b/docs/content/2.configuration/3.nuxt-auth-handler.md @@ -2,13 +2,23 @@ description: "Learn how to configure the NuxtAuthHandler that handles all authentication requests on the server-side" --- +::alert{type="info"} +This page is only relevant to you, if you are using the `authjs`-provider. +:: + # NuxtAuthHandler -After setting up [nuxt-auth inside your `nuxt.config.ts`](/nuxt-auth/configuration/nuxt-config) you can begin defining providers and other options inside your NuxtAuthHandler. +After following the [quick-start setup](/nuxt-auth/v0.6/getting-started/quick-start) and then optionally diving even deeper into the [`nuxt-auth` config inside your `nuxt.config.ts`](/nuxt-auth/v0.6/configuration/nuxt-config) you can begin defining providers and other options inside your `NuxtAuthHandler`. + +For development, using the quick-start setup will already bring you quite far. For a production deployment, you will have to additionally: +- set the `origin` by: + 1. exporting the `AUTH_ORIGIN`-environment variable _at runtime_ (higher precedence) + 2. setting the `origin`-key inside the `nuxt.config.ts` config _at build-time_ (lower precendence) +- set a secret inside the `NuxtAuthHandler` config ## Creating the `NuxtAuthHandler` -In order to create your own `NuxtAuthHandler`, create the file `~/server/api/auth/[...].ts`. This file will automatically set up the authentication API that responds to all requests going to `https://localhost/api/auth/*`. If you wish you can also use a custom file location and api path, however this change will need to be reflected in the [basePath](/nuxt-auth/configuration/nuxt-config#basepath), which is configured in the [nuxt.config.ts](/nuxt-auth/configuration/nuxt-config). +In order to create your own `NuxtAuthHandler`, create the file `~/server/api/auth/[...].ts`. This file will automatically set up the authentication API that responds to all requests going to `https://localhost/api/auth/*`. If you wish you can also use a custom file location and api path, however this change will need to be reflected in the [basePath](/nuxt-auth/v0.6/configuration/nuxt-config#basepath), which is configured in the [nuxt.config.ts](/nuxt-auth/v0.6/configuration/nuxt-config). ::alert{type="warning"} The filename must be `[...].ts` - this is a so-called "catch-all" route, read more [in the Nuxt catch-all docs](https://nuxt.com/docs/guide/directory-structure/server#catch-all-route). @@ -92,9 +102,7 @@ export default NuxtAuthHandler({ ``` :: -::alert{type="info"} The `NuxtAuthHandler` accepts [all options that NextAuth.js accepts for its API initialization](https://next-auth.js.org/configuration/options#options). Use this place to configure authentication providers (oauth-Google, credential flow, ...), your `secret`, add callbacks for authentication events, configure a custom logger and more. Read the [`NextAuth.js` docs to see all possible options](https://next-auth.js.org/configuration/options#options). -:: ### secret @@ -128,4 +136,4 @@ export default NuxtAuthHandler({ ## Further Examples -Checkout the [provider examples](/nuxt-auth/recipes) to see different examples of provider configurations, e.g., for Strapi or Directus. +Checkout the [provider recipes](/nuxt-auth/v0.6/recipes) to see different examples of provider configurations, e.g., for Strapi or Directus. diff --git a/docs/content/3.application-side/1.index.md b/docs/content/3.application-side/1.index.md index a527d581..dc9ec9d4 100644 --- a/docs/content/3.application-side/1.index.md +++ b/docs/content/3.application-side/1.index.md @@ -6,12 +6,9 @@ description: "Application-side usage of `nuxt-auth` for Vue / Nuxt 3 apps." On the application-side this module offers: ::list{type="success"} -- [`useAuth` composable for session access and management](/nuxt-auth/application-side/session-access-and-management) -::alert{type="info"} -Prior to v0.5.0 `useAuth()` was called `useSession()`. -:: -- [Creation of custom sign-in pages](/nuxt-auth/application-side/custom-sign-in-page) -- [Middleware to protect your application on the application side](/nuxt-auth/application-side/protecting-pages) +- [`useAuth` composable for session access and management](/nuxt-auth/v0.6/application-side/session-access-and-management) +- [Creation of custom sign-in pages](/nuxt-auth/v0.6/application-side/custom-sign-in-page) +- [Middleware to protect your application on the application side](/nuxt-auth/v0.6/application-side/protecting-pages) :: -Application-side usage refers to any code like pages, components or composables that are part of the universal server- and client-side rendering of Nuxt, see more in the [glossary](/nuxt-auth/resources/glossary). +Application-side usage refers to any code like pages, components or composables that are part of the universal server- and client-side rendering of Nuxt, see more in the [glossary](/nuxt-auth/v0.6/resources/glossary). diff --git a/docs/content/3.application-side/2.session-access-and-management.md b/docs/content/3.application-side/2.session-access-and-management.md index c5bfd318..a6fea5eb 100644 --- a/docs/content/3.application-side/2.session-access-and-management.md +++ b/docs/content/3.application-side/2.session-access-and-management.md @@ -1,11 +1,10 @@ # Session Access and Management -::alert{type="info"} -Prior to v0.5.0 `useAuth()` was called `useSession()`. -:: -The `useAuth` composable is your main gateway to accessing and manipulating session-state and data. Here's the main methods you can use: +## `useAuth` Composable -```ts +The `useAuth` composable is your main gateway to accessing and manipulating session-state and data. Here's the main methods you can use: +::code-group +```ts [authjs] const { status, data, @@ -17,7 +16,7 @@ const { signOut, } = useAuth() -// Session status, either `unauthenticated`, `loading`, `authenticated`, see https://next-auth.js.org/getting-started/client#signout +// Session status, either `unauthenticated`, `loading`, `authenticated` status.value // Session data, either `undefined` (= authentication not attempted), `null` (= user unauthenticated), `loading` (= session loading in progress), see https://next-auth.js.org/getting-started/client#signout @@ -26,7 +25,7 @@ data.value // Time at which the session was last refreshed, either `undefined` if no refresh was attempted or a `Date`-object of the time the refresh happened lastRefreshedAt.value -// Get / Reload the current session from the server, pass `{ required: true }` to force a login if no session exists, see https://next-auth.js.org/getting-started/client#getsession +// Get / Reload the current session from the server, pass `{ required: true }` to force a login if no session exists await getSession() // Get the current CSRF token, usually you do not need this function, see https://next-auth.js.org/getting-started/client#signout @@ -53,10 +52,61 @@ await signOut() // Trigger a sign-out and send the user to the sign-out page afterwards await signOut({ callbackUrl: '/signout' }) ``` +```ts [local] +const { + status, + data, + token, + lastRefreshedAt, + getSession, + signUp, + signIn, + signOut, +} = useAuth() + +// Session status, either `unauthenticated`, `loading`, `authenticated` +status.value + +// Session data, either `undefined` (= authentication not attempted), `null` (= user unauthenticated), or session / user data your `getSession`-endpoint returns +data.value + +// The fetched token that can be used to authenticate future requests. E.g., a JWT-Bearer token like so: `Bearer eyDFSJKLDAJ0-3249PPRFK3P5234SDFL;AFKJlkjdsjd.dsjlajhasdji89034` +token.value + +// Time at which the session was last refreshed, either `undefined` if no refresh was attempted or a `Date`-object of the time the refresh happened +lastRefreshedAt.value + +// Get / Reload the current session from the server, pass `{ required: true }` to force a login if no session exists +await getSession() + +// Trigger a sign-in, where `credentials` are the credentials your sign-in endpoint expected, e.g. `{ username: 'bernd', password: 'hunter2' }` +await signIn(credentials) + +// Trigger a sign-in with a redirect afterwards +await signIn(credentials, { callbackUrl: '/protected' }) + +// Trigger a sign-in with a redirect afterwards to an external page (if set, this will cause a hard refresh of the page) +await signIn(credentials, { callbackUrl: 'https://sidebase.io', external: true }) + +// Trigger a sign-out +await signOut() + +// Trigger a sign-out and send the user to the sign-out page afterwards +await signOut({ callbackUrl: '/signout' }) +``` +:: + +## `SessionData` -Session `data.value` has the following interface: +As described above you can use: ```ts -interface DefaultSession { +const { data } = useAuth() +``` + +to access the session-data of the currently logged in user. Depending on the provider you use, this data will be typed differently: +::code-group +```ts [authjs] +interface SessionData { user?: { name?: string | null; email?: string | null; @@ -65,28 +115,134 @@ interface DefaultSession { expires: ISODateString; } ``` +```ts [local] +// Option A: No explicit configuration +inferface SessionData { + id: string | number +} + +// Option B: You configured `auth.provider.sessionDataType` to something like ` { id: 'string', email: 'string', name: 'string', role: 'admin | guest | account' }` +inferface SessionData { + id: string + email: string + name: string + role: 'admin' | 'guest' | 'account' +} +``` +:: + +### About `auth.provider.sessionDataType` + +This is a configuration option available to dynamically type the `SessionData` that the `local` provider will return when accessing `data.value`. Read more about this in the [nuxt.config.ts configuration documentation](/nuxt-auth/v0.6/configuration/nuxt-config) of the `local` provider. -Note that this is only set when the use is logged-in and when the provider used to login the user provides the fields. +`nuxt-auth` uses [unjs/knitwork](https://github.com/unjs/knitwork) to generate the correct typescript interface from the type you provide. + +## Force refetching the session (`local` provider only) + +Calling `getSession` will by default **only** refetch the current session if the token returned by `useAuthState` is defined. +Passing the `{ force: true }` option will always update the current session: + +::code-group +```ts [local] +// force update the current session +await getSession({ force: true }) +``` +:: ## Redirects -You can also pass the `callbackUrl` option to both the `signIn`, the `signOut` and the `getSession` method. This allows you to redirect a user to a certain pages, after they've completed the action. This can be useful when a user attempts to open a page (`/protected`) but has to go through external authentication (e.g., via their google account) first. +You can also pass the `callbackUrl` option to both the `signIn`, the `signOut` and the `getSession` methods. This allows you to redirect a user to a certain pages, after they've completed the action. This can be useful when a user attempts to open a page (`/protected`) but has to go through external authentication (e.g., via their google account) first. You can use it like: -```ts -await signIn({ callbackUrl: '/protected' }) +::code-group +```ts [authjs] +await signIn(undefined, { callbackUrl: '/protected' }) + +await signOut({ callbackUrl: '/protected' }) + +await getSession({ callbackUrl: '/protected' }) ``` +```ts [local] +const credentials = { username: 'bernd', password: 'hunter2' } +await signIn(credentials, { callbackUrl: '/protected' }) -to redirect the user to the protected page they wanted to access _after_ they've been authenticated. +await signOut(credentials, { callbackUrl: '/protected' }) -You can do the same for signing out the user: -```ts -await signOut({ callbackUrl: '/protected' }) +await getSession(credentials, { callbackUrl: '/protected' }) ``` +:: + +## `useAuthState` Composable + +The `useAuthState` composable is the underlying storage layer to access the session-state and data. Here's the main methods and properties you can use: + +::code-group +```ts [authjs] +const { + status, + loading, + data, + lastRefreshedAt +} = useAuth() + +// Session status, either `unauthenticated`, `loading`, `authenticated` +status.value + +// Whether any http request is still pending +loading.value -E.g., to redirect the user away from the already loaded, protected, page after signout (else, you will have to handle the redirect yourself). +// Session data, either `undefined` (= authentication not attempted), `null` (= user unauthenticated), `loading` (= session loading in progress), see https://next-auth.js.org/getting-started/client#signout +data.value + +// Time at which the session was last refreshed, either `undefined` if no refresh was attempted or a `Date`-object of the time the refresh happened +lastRefreshedAt.value +``` +```ts [local] +const { + status, + loading, + data, + lastRefreshedAt, + token, + rawToken, + getToken, + clearToken +} = useAuth() + +// Session status, either `unauthenticated`, `loading`, `authenticated` +status.value + +// Whether any http request is still pending +loading.value + +// Session data, either `undefined` (= authentication not attempted), `null` (= user unauthenticated), or session / user data your `getSession`-endpoint returns +data.value + +// Time at which the session was last refreshed, either `undefined` if no refresh was attempted or a `Date`-object of the time the refresh happened +lastRefreshedAt.value + +// The fetched token that can be used to authenticate future requests. E.g., a JWT-Bearer token like so: `Bearer eyDFSJKLDAJ0-3249PPRFK3P5234SDFL;AFKJlkjdsjd.dsjlajhasdji89034` +token.value + +// Cookie that containes the raw fetched token string. This token won't contain any modification or prefixes like `Bearer` or any other. +rawToken.value + +// Helper method to quickly set a new token (alias for rawToken.value = 'xxx') +setToken('new token') + +// Helper method to quickly delete the token cookie (alias for rawToken.value = null) +clearToken() +``` +:: + +::alert{type="warning"} +Local provider: Note that you will have to manually call `getSession` from `useAuth` composable in order to refresh the new user state when using `setToken`, `clearToken` or manually updating `rawToken.value`: +:: -You may also pass specify a callback for the `getSession` utility: ```ts -await getSession({ callbackUrl: '/protected' }) +const { getSession } = useAuth() +const { setToken } = useAuthState() +// ... +setToken('...') +await getSession() ``` diff --git a/docs/content/3.application-side/3.custom-sign-in-page.md b/docs/content/3.application-side/3.custom-sign-in-page.md index 5bba78ae..2100c45c 100644 --- a/docs/content/3.application-side/3.custom-sign-in-page.md +++ b/docs/content/3.application-side/3.custom-sign-in-page.md @@ -1,16 +1,15 @@ # Custom sign-in Page +## Provider: `authjs` + To create a custom sign-in page you will need to: 1. Create the custom sign-in page: Creating the actual page your user will enter their credentials on OR select their oauth provider (e.g., google, azure, ...) -2. Configure `nuxt-auth` to redirect to the custom sign-in page: If a sign-in is triggered or a session check fails, `nuxt-auth` has to forward you to your custom sign-in page, instead of the `nuxt-auth` builtin sign-in page +2. Configure the `authjs`-backend-auth-handler to redirect to the custom sign-in page: If a sign-in is triggered or a session check fails, the `authjs`-backend-auth-handler has to forward you to your custom sign-in page, instead of the the `authjs`-backend-auth-handler builtin sign-in page 3. Optional: Disable the `nuxt-auth` global protection middleware for the custom page if you have it enabled -## Create the Custom sign-in Page +### Create the Custom sign-in Page To create your custom sign-in page you can use `signIn` to directly start a provider-flow once the user selected it, e.g., by clicking on a button on your custom sign-in page. Here is a very simple sign-in page that either directly starts a github-oauth sign-in flow or directly signs in the user via the credentials flow: -::alert{type="info"} -Prior to v0.5.0 `useAuth()` was called `useSession()`. -:: ```vue