Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(#673): migrate to AuthJS #818

Merged
merged 12 commits into from
Jul 25, 2024
Merged
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ Then visit the [Quick Start documentation](https://auth.sidebase.io/guide/gettin
## Features

`@sidebase/nuxt-auth` is a library with the goal of supporting authentication for any universal Nuxt 3 application. At the moment three providers are supported:
- [`authjs`](https://auth.sidebase.io/guide/authjs/quick-start): for non-static apps that want to use [Auth.js / NextAuth.js](https://github.com/nextauthjs/next-auth) to offer the reliability & convenience of a 23k star library to the Nuxt 3 ecosystem with a native developer experience (DX)
- [`authjs`](https://auth.sidebase.io/guide/authjs/quick-start): for non-static apps that want to use [Auth.js](https://authjs.dev/) to offer the reliability & convenience of a 23k star library to the Nuxt 3 ecosystem with a native developer experience (DX)
- [`local`](https://auth.sidebase.io/guide/local/quick-start): for static pages that rely on an external backend with a credential flow for authentication.
- [`refresh`](https://auth.sidebase.io/guide/local/quick-start#refresh-token): for static pages that rely on an external backend with a credential flow and refresh tokens for authentication.

Expand Down
11 changes: 6 additions & 5 deletions docs/guide/authjs/nuxt-auth-handler.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# NuxtAuthHandler

The NuxtAuthHandler is an adaptation of the [NextAuthHandler](https://next-auth.js.org/configuration/options) built into AuthJS. You can learn more about how to setup a minimal version of the NuxtAuthHandler in the [Quick Start section](/guide/authjs/quick-start#nuxtauthhandler).
The NuxtAuthHandler is an adaptation of the [AuthConfig](https://authjs.dev/reference/core#authconfig) built into AuthJS. You can learn more about how to setup a minimal version of the NuxtAuthHandler in the [Quick Start section](/guide/authjs/quick-start#nuxtauthhandler).


## Secret
Expand All @@ -26,16 +26,17 @@ export default defineNuxtConfig({
```

``` txt [.env]
# This will overwrite the default secret set in the nuxt config.
NUXT_AUTH_SECRET="YOUR-SUPER-SECURE-SECRET"
```

:::

## Providers

The providers are the registered authentication methods that your users can use to login to your application. NuxtAuth provides a number of preconfigured providers you can use to quickly bootstrap your project. These include OAuth providers, [email-based providers](https://next-auth.js.org/configuration/providers/email) (Magic URLs) and a [credentials provider](https://next-auth.js.org/configuration/providers/credentials). In addition to using a pre-built provider, you can also create your own provider.
The providers are the registered authentication methods that your users can use to login to your application. NuxtAuth provides a number of preconfigured providers you can use to quickly bootstrap your project. These include OAuth providers, [email-based providers](https://authjs.dev/getting-started/authentication/email) (Magic URLs) and a [credentials provider](https://authjs.dev/getting-started/authentication/credentials). In addition to using a pre-built provider, you can also create your own provider.

You can find an overview of all the prebuilt providers [here](https://next-auth.js.org/providers/). If you want to create your own provider, please visit the [NextAuth docs](https://next-auth.js.org/configuration/providers/oauth#using-a-custom-provider).
You can find an overview of all the prebuilt providers [here](https://authjs.dev/reference/core/providers). If you want to create your own provider, please visit the [AuthJS docs](https://authjs.dev/guides/configuring-oauth-providers#use-your-own-provider).


## Callbacks
Expand Down Expand Up @@ -80,7 +81,7 @@ Some uses-cases for each callback could be:
- `session`: Fetch and inject additional data into the session. Read more [here](/guide/authjs/session-data).
- `jwt`: Inject or update data inside the JWT token and manage refresh and access tokens.

You can read more on each of these callbacks, what data they provide and what return value they expect on the offical [NextAuth docs](https://next-auth.js.org/configuration/callbacks).
You can read more on each of these callbacks, what data they provide and what return value they expect on the offical [AuthJS docs](https://authjs.dev/reference/core#callbacks).

## Events

Expand All @@ -102,7 +103,7 @@ export default NuxtAuthHandler({
})
```

You can read more on each of these events and what data they provide on the offical [NextAuth docs](https://next-auth.js.org/configuration/events).
You can read more on each of these events and what data they provide on the offical [AuthJS docs](https://authjs.dev/reference/core#events).

## Pages

Expand Down
27 changes: 10 additions & 17 deletions docs/guide/authjs/quick-start.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,18 @@ This guide is for setting up `@sidebase/nuxt-auth` with the AuthJS Provider, whi

## Installation

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:
If you want to use the AuthJS provider, you have to install [`@auth/core`](https://www.npmjs.com/package/@auth/core). With all package managers except npm you must manually install the peer dependency alongside nuxt-auth:

::: code-group

```bash [pnpm]
pnpm i [email protected]
pnpm i @auth/core
```

```bash [yarn]
yarn add [email protected]
yarn add @auth/core
```

::: warning
Due to a breaking change in NextAuth, nuxt-auth is only compatible with NextAuth versions under v4.23.0. We recommend pinning the version to `4.21.1`. Read more [here](https://github.com/sidebase/nuxt-auth/issues/514).
:::

## Configuration
Expand Down Expand Up @@ -70,7 +68,7 @@ Whether to add a callbackUrl to sign in requests. Setting this to a string-value

As a next step, create your NuxtAuthHandler under `~/server/api/auth/[...].ts`. Inside it you can configure the authentication provider you want to use, how the JWT Token is created and managed as well as how your sessions will be composed. The NuxtAuthHander will automatically create all required API endpoints to handle authentication inside your application.

The NuxtAuthHandler is an adaptation of the [NextAuthHandler](https://next-auth.js.org/configuration/options) built into AuthJS. Inside the NuxtAuthHandler you can configure:
The NuxtAuthHandler is an adaptation of the [AuthConfig](https://authjs.dev/reference/core#authconfig) built into AuthJS. Inside the NuxtAuthHandler you can configure:

- **OAuth providers**: _How can users login to your application?_
- **Adapters**: _How are sessions saved? (e.g. JWT Token, Database etc.)_
Expand All @@ -89,30 +87,25 @@ export default NuxtAuthHandler({

### Adding a provider

After creating your NuxtAuthHandler, you can begin by adding a provider. You can find an overview of all the avalible providers [here](https://next-auth.js.org/providers/). For this example we will add the GitHub provider.
After creating your NuxtAuthHandler, you can begin by adding a provider. You can find an overview of all the avalible providers [here](https://authjs.dev/reference/core/providers). For this example we will add the GitHub provider.

```ts
import GithubProvider from 'next-auth/providers/github'
import GithubProvider from '@auth/core/providers/github'
import { NuxtAuthHandler } from '#auth'

export default NuxtAuthHandler({
// A secret string you define, to ensure correct encryption
secret: 'your-secret-here',
providers: [
// @ts-expect-error Use .default here for it to work during SSR.
GithubProvider.default({
GithubProvider({
clientId: 'your-client-id',
clientSecret: 'your-client-secret'
})
]
})
```

:::warning
After importing your provider from `next-auth/providers/[PROVIDER]`, call it using `.default()` inside of the providers array configuration. This is required for SSR to properly function.
:::

The NuxtAuthHandler accepts [all options that NextAuth.js](https://next-auth.js.org/configuration/options#options) accepts for its API initialization. Use this place to configure authentication providers (OAuth, credential flow, ...), your secret, add callbacks for authentication events, configure a custom logger and more. Read the [NextAuth.js docs](https://next-auth.js.org/configuration/options#options) to see all possible options.
The NuxtAuthHandler accepts [all options that AuthJS](https://authjs.dev/reference/core#authconfig) accepts for its API initialization. Use this place to configure authentication providers (OAuth, credential flow, ...), your secret, add callbacks for authentication events, configure a custom logger and more. Read the [AuthJS docs](https://authjs.dev/reference/core) to see all possible options.

### Setting a secret

Expand All @@ -132,14 +125,14 @@ export default NuxtAuthHandler({
::: details Full code
```ts
// file: ~/server/api/auth/[...].ts
import GithubProvider from 'next-auth/providers/github'
import GithubProvider from '@auth/core/providers/github'
import { NuxtAuthHandler } from '#auth'

export default NuxtAuthHandler({
secret: useRuntimeConfig().authSecret,
providers: [
// @ts-expect-error Use .default here for it to work during SSR.
GithubProvider.default({
GithubProvider({
clientId: 'your-client-id',
clientSecret: 'your-client-secret'
})
Expand Down
2 changes: 1 addition & 1 deletion docs/guide/authjs/server-side/jwt-access.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export default eventHandler(async (event) => {
})
```

The function behaves identical to the [`getToken` function from NextAuth.js](https://next-auth.js.org/tutorials/securing-pages-and-api-routes#using-gettoken) with one change: you have to pass in the h3-`event` instead of `req`. This is due to how cookies can be accessed on h3: not via `req.cookies` but rather via `useCookies(event)`.
The function behaves identical to the [`getToken` function from AuthJS](https://authjs.dev/reference/core/jwt#gettoken) with one change: you have to pass in the h3-`event` instead of `req`. This is due to how cookies can be accessed on h3: not via `req.cookies` but rather via `useCookies(event)`.

You do not need to pass in any further parameters like `secret`, `secureCookie`, ... They are automatically inferred to the values you configured if not set and reading the token will work out of the box. You _may_ pass these options, e.g., to get the raw, encoded JWT token you can pass `raw: true`.

Expand Down
4 changes: 2 additions & 2 deletions docs/guide/authjs/server-side/rest-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ aside: false

# REST API

All endpoints that NextAuth.js supports are also supported by `nuxt-auth`:
All endpoints that AuthJS supports are also supported by `nuxt-auth`:

| Endpoint | Request | Description |
|-----------------------------------|:-------------|:---------------------------------------------------------------|
Expand All @@ -18,4 +18,4 @@ All endpoints that NextAuth.js supports are also supported by `nuxt-auth`:

The `baseURL` is `/api/auth` per default and [can be configured in the `nuxt.config.ts`](/guide/application-side/configuration#baseurl).

You can directly interact with these API endpoints if you wish to, it's probably a better idea to use `useAuth` where possible though. [See the full rest API documentation of NextAuth.js here](https://next-auth.js.org/getting-started/rest-api).
You can directly interact with these API endpoints if you wish to, it's probably a better idea to use `useAuth` where possible though.
2 changes: 1 addition & 1 deletion docs/guide/authjs/server-side/session-access.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default eventHandler(async (event) => {
})
```

This is inspired by [the `getServerSession`](https://next-auth.js.org/tutorials/securing-pages-and-api-routes#securing-api-routes) of NextAuth.js. It also avoids an external HTTP `GET` request to the `/api/auth/sessions` endpoint, instead directly calling a pure JS-method.
This is inspired by [the `getServerSession`](https://authjs.dev/getting-started/session-management/protecting) of AuthJS. It also avoids an external HTTP `GET` request to the `/api/auth/sessions` endpoint, instead directly calling a pure JS-method.

:::warning Note:
If you use [Nuxt's `useFetch`](https://nuxt.com/docs/api/composables/use-fetch) from your app-components to fetch data from an endpoint that uses `getServerSession` or `getToken` you will need to manually pass along cookies as [Nuxt 3 universal rendering](https://nuxt.com/docs/guide/concepts/rendering#universal-rendering) will not do this per-default when it runs on the server-side. Not passing along cookies will result in `getServerSession` returning `null` when it is called from the server-side as no auth cookies will exist. Here's an example that manually passes along cookies:
Expand Down
10 changes: 5 additions & 5 deletions docs/guide/authjs/session-data.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,13 +87,13 @@ const { data } = useAuth()

When modifying the session or JWT objects, you may want to adjust the types accordingly, to ensure that you get proper intellisense and type support. [Module Augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation) can be used to inject additional type declarations into installed modules to overwrite or add additional data.

Begin by creating a new typescript file in the root of your project named: `next-auth.d.ts`. Typescript will automatically recognize that this file is augmenting the module types of `next-auth` (running under the hood).
Begin by creating a new typescript file in the root of your project named: `auth.d.ts`. Typescript will automatically recognize that this file is augmenting the module types of `@auth/core` (running under the hood).
zoey-kaiser marked this conversation as resolved.
Show resolved Hide resolved

```ts
// file: ~/next-auth.d.ts
import type { DefaultSession } from 'next-auth'
// file: ~/auth.d.ts
import type { DefaultSession } from '@auth/core/types'

declare module 'next-auth' {
declare module 'auth' {
/* Returned by `useAuth`, `getSession` and `getServerSession` */
interface Session extends DefaultSession {
user: {
Expand All @@ -108,7 +108,7 @@ declare module 'next-auth' {
In addition to modifying the `session` data types, you can also extend the types of the JWT token. This allows you to receive proper type support when accessing the JWT token inside the NuxtAuthHandler or when calling `getToken` on the server side.

```ts
// file: ~/next-auth.d.ts
// file: ~/auth.d.ts
declare module 'next-auth/jwt' {
/** Returned by the `jwt` callback and `getToken` */
interface JWT {
Expand Down
27 changes: 2 additions & 25 deletions docs/guide/getting-started/introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,31 +26,8 @@ Through a direct integration into Nuxt, you can access and utlize the user sessi

## Common questions

### Why does NuxtAuth require NextAuth?
### Why does NuxtAuth require AuthJS?

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 >22.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.
The `authjs` provider is able to provide all of its features by wrapping [Auth.js](https://authjs.dev/) under the hood. This gives the reliability & convenience of a >22.000 github star library to the Nuxt 3 ecosystem with a native nuxt developer experience (DX). Wrapping Auth.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 Auth.js guides and documentation to achieve things with the authjs provider of nuxt-auth.

NuxtAuth 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.

### What is the difference between Auth.js and NextAuth?

We use authjs everywhere to mean authjs and next-auth interchangably as next-auth is currently transitioning to become authjs (branded name: [Auth.js](https://authjs.dev/)).

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/issues/673). 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.

### NextAuth `GHSA-v64w-49xw-qq89` vulnerability

NuxtAuth wraps NextAuth `v4.21.1` to provide the reliability and convenience of countless preconfigured and tested OAuth providers.In `v4.22` and above, NextAuth has changed their package exports, blocking NuxtAuth users from using the newer versions.

NextAuth versions under `4.22` are impacted by vulnerability [GHSA-v64w-49xw-qq89](https://github.com/advisories/GHSA-v64w-49xw-qq89), after doing an internal investigation into this vulnerability we could determine that NuxtAuth applications using this version are not affected.

::: details Further details
---
#### Description of the vulnerability
The vulnerability [GHSA-v64w-49xw-qq89](https://github.com/advisories/GHSA-v64w-49xw-qq89) only affects applications that rely on the default [Middleware authorization](https://next-auth.js.org/configuration/nextjs#middleware) provided by NextAuth.

The vulnerability allows attackers to create/mock a user, by accessing the JWT from an interrupted OAuth sign-in flow. They can then manually override the session cookie and simulate a login. However, doing this does **not** give access to the users data or permissions, but can allow attackers to view the layouts of protected pages.

#### Why does it not effect NuxtAuth?
As the affected middleware is written for Next.js, we wrote our own [custom middleware](https://github.com/sidebase/nuxt-auth/blob/main/src/runtime/middleware/auth.ts) for NuxtAuth that is not affected by the vulnerability.
:::
2 changes: 1 addition & 1 deletion docs/resources/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ During research it became clear that implementing everything from scratch will b
- hard to maintain as authentication providers come and go,
- hard to build initial trust for as authentication is important and cannot go wrong,

In order to avoid these problems without taking forever (leaving Nuxt without an authentication library in the meantime), we decided to investigate if we can wrap [NextAuth.js](https://github.com/nextauthjs/next-auth), the most popular authentication library in the Next.js ecosystem by far and a trusted, well maintained one at that!
In order to avoid these problems without taking forever (leaving Nuxt without an authentication library in the meantime), we decided to investigate if we can wrap [AuthJS](https://authjs.dev/), the most popular authentication library in the Next.js ecosystem by far and a trusted, well maintained one at that!

In our investigation we found prior attempts to make NextAuth.js framework agnostic. These have more or less come to fruition, so far mostly resulting in some PoCs and example apps. Looking at these was quite helpful to get started. In particular, big pushes in the right direction came from:

Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,15 @@
"ufo": "^1.5.3"
},
"peerDependencies": {
"next-auth": "~4.21.1"
"next-auth": "5.0.0-beta.19"
phoenix-ru marked this conversation as resolved.
Show resolved Hide resolved
},
"devDependencies": {
"@nuxt/module-builder": "^0.5.5",
"@nuxt/schema": "^3.11.2",
"@nuxtjs/eslint-config-typescript": "^12.1.0",
"@types/node": "^18.19.31",
"eslint": "^8.57.0",
"next-auth": "5.0.0-beta.19",
"nuxt": "^3.11.2",
"ofetch": "^1.3.4",
"ts-essentials": "^9.4.2",
Expand Down
Loading
Loading