mirror of
https://github.com/SrIzan10/next-auth.git
synced 2026-05-01 10:55:20 +00:00
Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
172e79cb04 | ||
|
|
46d5c76605 | ||
|
|
438efd8a9b | ||
|
|
d8d497cc91 | ||
|
|
6152c8afbb | ||
|
|
5ae6f6118c | ||
|
|
96ff048b59 | ||
|
|
e80f6e936d | ||
|
|
6b5a215fb2 | ||
|
|
782482b9f4 | ||
|
|
2d364f246a |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -11,6 +11,8 @@ npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
yarn.lock
|
||||
|
||||
# Dependencies
|
||||
node_modules
|
||||
|
||||
@@ -37,4 +39,4 @@ www/providers.json
|
||||
/_work
|
||||
|
||||
# Prisma migrations
|
||||
/prisma/migrations
|
||||
/prisma/migrations
|
||||
|
||||
@@ -23,9 +23,9 @@
|
||||
<img src="https://img.shields.io/github/stars/nextauthjs/next-auth" alt="Github Stars" />
|
||||
</a>
|
||||
<a href="https://www.npmjs.com/package/next-auth">
|
||||
<img src="https://img.shields.io/github/v/release/nextauthjs/next-auth" alt="Github Stable Release" />
|
||||
<img src="https://img.shields.io/github/v/release/nextauthjs/next-auth?label=latest" alt="Github Stable Release" />
|
||||
</a>
|
||||
<img src="https://img.shields.io/github/v/release/nextauthjs/next-auth?include_prereleases" alt="Github Prelease" />
|
||||
<img src="https://img.shields.io/github/v/release/nextauthjs/next-auth?include_prereleases&label=prerelease&sort=semver" alt="Github Prelease" />
|
||||
</p>
|
||||
</p>
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ export default (options) => {
|
||||
const defaultAvatarNumber = parseInt(profile.discriminator) % 5
|
||||
profile.image_url = `https://cdn.discordapp.com/embed/avatars/${defaultAvatarNumber}.png`
|
||||
} else {
|
||||
const format = profile.premium_type === 1 || profile.premium_type === 2 ? 'gif' : 'png'
|
||||
const format = profile.avatar.startsWith('a_') ? 'gif' : 'png'
|
||||
profile.image_url = `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}.${format}`
|
||||
}
|
||||
return {
|
||||
|
||||
@@ -108,7 +108,7 @@ async function getProfile ({ profileData, tokens, provider, user }) {
|
||||
|
||||
logger.debug('PROFILE_DATA', profileData)
|
||||
|
||||
const profile = await provider.profile(profileData)
|
||||
const profile = await provider.profile(profileData, tokens)
|
||||
// Return profile, raw profile and auth provider details
|
||||
return {
|
||||
profile: {
|
||||
|
||||
@@ -10,7 +10,7 @@ export default async function email (email, provider, options) {
|
||||
const secret = provider.secret || options.secret
|
||||
|
||||
// Generate token
|
||||
const token = provider.generateVerificationToken?.() ?? randomBytes(32).toString('hex')
|
||||
const token = await provider.generateVerificationToken?.() ?? randomBytes(32).toString('hex')
|
||||
|
||||
// Send email with link containing token (the unhashed version)
|
||||
const url = `${baseUrl}${basePath}/callback/${encodeURIComponent(provider.id)}?email=${encodeURIComponent(email)}&token=${encodeURIComponent(token)}`
|
||||
|
||||
@@ -9,14 +9,34 @@ export default function renderPage (req, res) {
|
||||
const { baseUrl, basePath, callbackUrl, csrfToken, providers, theme } = req.options
|
||||
|
||||
res.setHeader('Content-Type', 'text/html')
|
||||
function send (html) {
|
||||
res.send(`<!DOCTYPE html><head><style type="text/css">${css()}</style><meta name="viewport" content="width=device-width, initial-scale=1"></head><body class="__next-auth-theme-${theme}"><div class="page">${html}</div></body></html>`)
|
||||
function send ({ html, title }) {
|
||||
res.send(`<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><style>${css()}</style><title>${title}</title></head><body class="__next-auth-theme-${theme}"><div class="page">${html}</div></body></html>`)
|
||||
}
|
||||
|
||||
return {
|
||||
signin (props) { send(signin({ csrfToken, providers, callbackUrl, ...req.query, ...props })) },
|
||||
signout (props) { send(signout({ csrfToken, baseUrl, basePath, ...props })) },
|
||||
verifyRequest (props) { send(verifyRequest({ baseUrl, ...props })) },
|
||||
error (props) { send(error({ basePath, baseUrl, res, ...props })) }
|
||||
signin (props) {
|
||||
send({
|
||||
html: signin({ csrfToken, providers, callbackUrl, ...req.query, ...props }),
|
||||
title: 'Sign In'
|
||||
})
|
||||
},
|
||||
signout (props) {
|
||||
send({
|
||||
html: signout({ csrfToken, baseUrl, basePath, ...props }),
|
||||
title: 'Sign Out'
|
||||
})
|
||||
},
|
||||
verifyRequest (props) {
|
||||
send({
|
||||
html: verifyRequest({ baseUrl, ...props }),
|
||||
title: 'Verify Request'
|
||||
})
|
||||
},
|
||||
error (props) {
|
||||
send({
|
||||
html: error({ basePath, baseUrl, res, ...props }),
|
||||
title: 'Error'
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,52 +112,6 @@ callbacks: {
|
||||
The redirect callback may be invoked more than once in the same flow.
|
||||
:::
|
||||
|
||||
## Session callback
|
||||
|
||||
The session callback is called whenever a session is checked.
|
||||
|
||||
e.g. `getSession()`, `useSession()`, `/api/auth/session`
|
||||
|
||||
* When using database sessions, the User object is passed as an argument.
|
||||
* When using JSON Web Tokens for sessions, the JWT payload is provided instead.
|
||||
|
||||
```js title="pages/api/auth/[...nextauth].js"
|
||||
...
|
||||
callbacks: {
|
||||
/**
|
||||
* @param {object} session Session object
|
||||
* @param {object} token User object (if using database sessions)
|
||||
* JSON Web Token (if not using database sessions)
|
||||
* @return {object} Session that will be returned to the client
|
||||
*/
|
||||
async session(session, token) {
|
||||
if(token?.accessToken) {
|
||||
// Add property to session, like an access_token from a provider
|
||||
session.accessToken = token.accessToken
|
||||
}
|
||||
return session
|
||||
}
|
||||
}
|
||||
...
|
||||
```
|
||||
|
||||
:::tip
|
||||
When using JSON Web Tokens the `jwt()` callback is invoked before the `session()` callback, so anything you add to the
|
||||
JSON Web Token will be immediately available in the session callback, like for example an `access_token` from a provider.
|
||||
:::
|
||||
|
||||
:::tip
|
||||
To better represent its value, when using a JWT session, the second parameter should be called `token` (This is the same thing you return from the `jwt` callback). If you use a database, call it `user`.
|
||||
:::
|
||||
|
||||
:::warning
|
||||
The session object is not persisted server side, even when using database sessions - only data such as the session token, the user, and the expiry time is stored in the session table.
|
||||
|
||||
If you need to persist session data server side, you can use the `accessToken` returned for the session as a key - and connect to the database in the `session()` callback to access it. Session `accessToken` values do not rotate and are valid as long as the session is valid.
|
||||
|
||||
If using JSON Web Tokens instead of database sessions, you should use the User ID or a unique key stored in the token (you will need to generate a key for this yourself on sign in, as access tokens for sessions are not generated when using JSON Web Tokens).
|
||||
:::
|
||||
|
||||
## JWT callback
|
||||
|
||||
This JSON Web Token callback is called whenever a JSON Web Token is created (i.e. at sign
|
||||
@@ -206,3 +160,47 @@ NextAuth.js does not limit how much data you can store in a JSON Web Token, howe
|
||||
|
||||
If you need to persist a large amount of data, you will need to persist it elsewhere (e.g. in a database). You can store a key that can be used to look up that data in the `session()` callback.
|
||||
:::
|
||||
|
||||
## Session callback
|
||||
|
||||
The session callback is called whenever a session is checked. By default, only a subset of the token is returned for increased security. If you want to make something available you added to the token through the `jwt()` callback, you have to explicitely forward it here to make it available to the client.
|
||||
|
||||
e.g. `getSession()`, `useSession()`, `/api/auth/session`
|
||||
|
||||
* When using database sessions, the User object is passed as an argument.
|
||||
* When using JSON Web Tokens for sessions, the JWT payload is provided instead.
|
||||
|
||||
```js title="pages/api/auth/[...nextauth].js"
|
||||
...
|
||||
callbacks: {
|
||||
/**
|
||||
* @param {object} session Session object
|
||||
* @param {object} token User object (if using database sessions)
|
||||
* JSON Web Token (if not using database sessions)
|
||||
* @return {object} Session that will be returned to the client
|
||||
*/
|
||||
async session(session, token) {
|
||||
// Add property to session, like an access_token from a provider.
|
||||
session.accessToken = token.accessToken
|
||||
return session
|
||||
}
|
||||
}
|
||||
...
|
||||
```
|
||||
|
||||
:::tip
|
||||
When using JSON Web Tokens the `jwt()` callback is invoked before the `session()` callback, so anything you add to the
|
||||
JSON Web Token will be immediately available in the session callback, like for example an `access_token` from a provider.
|
||||
:::
|
||||
|
||||
:::tip
|
||||
To better represent its value, when using a JWT session, the second parameter should be called `token` (This is the same thing you return from the `jwt()` callback). If you use a database, call it `user`.
|
||||
:::
|
||||
|
||||
:::warning
|
||||
The session object is not persisted server side, even when using database sessions - only data such as the session token, the user, and the expiry time is stored in the session table.
|
||||
|
||||
If you need to persist session data server side, you can use the `accessToken` returned for the session as a key - and connect to the database in the `session()` callback to access it. Session `accessToken` values do not rotate and are valid as long as the session is valid.
|
||||
|
||||
If using JSON Web Tokens instead of database sessions, you should use the User ID or a unique key stored in the token (you will need to generate a key for this yourself on sign in, as access tokens for sessions are not generated when using JSON Web Tokens).
|
||||
:::
|
||||
|
||||
@@ -328,7 +328,7 @@ export default NextAuth({
|
||||
},
|
||||
warn(code, ...message) {
|
||||
log.warn(code, message)
|
||||
}
|
||||
},
|
||||
debug(code, ...message) {
|
||||
log.debug(code, message)
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ NextAuth.js automatically creates simple, unbranded authentication pages for han
|
||||
|
||||
The options displayed on the sign up page are automatically generated based on the providers specified in the options passed to NextAuth.js.
|
||||
|
||||
To add a custom login page, for example. You can use the `pages` option:
|
||||
To add a custom login page, you can use the `pages` option:
|
||||
|
||||
```javascript title="pages/api/auth/[...nextauth].js"
|
||||
...
|
||||
@@ -121,4 +121,4 @@ signIn('credentials', { username: 'jsmith', password: '1234' })
|
||||
|
||||
:::tip
|
||||
Remember to put any custom pages in a folder outside **/pages/api** which is reserved for API code. As per the examples above, a location convention suggestion is `pages/auth/...`.
|
||||
:::
|
||||
:::
|
||||
|
||||
@@ -78,7 +78,10 @@ As an example of what this looks like, this is the the provider object returned
|
||||
requestTokenUrl: "https://accounts.google.com/o/oauth2/auth",
|
||||
authorizationUrl: "https://accounts.google.com/o/oauth2/auth?response_type=code",
|
||||
profileUrl: "https://www.googleapis.com/oauth2/v1/userinfo?alt=json",
|
||||
async profile(profile) {
|
||||
async profile(profile, tokens) {
|
||||
// You can use the tokens, in case you want to fetch more profile information
|
||||
// For example several OAuth provider does not return e-mail by default.
|
||||
// Depending on your provider, will have tokens like `access_token`, `id_token` and or `refresh_token`
|
||||
return {
|
||||
id: profile.id,
|
||||
name: profile.name,
|
||||
|
||||
@@ -116,7 +116,7 @@ NextAuth.js records Refresh Tokens and Access Tokens on sign in (if supplied by
|
||||
|
||||
You can then look them up from the database or persist them to the JSON Web Token.
|
||||
|
||||
Note: NextAuth.js does not currently handle Access Token rotation for OAuth providers for you, if this is something you need, currently you will need to write the logic to handle that yourself.
|
||||
Note: NextAuth.js does not currently handle Access Token rotation for OAuth providers for you, however you can check out [this tutorial](/tutorials/refresh-token-rotation) if you want to implement it.
|
||||
|
||||
### When I sign in with another account with the same email address, why are accounts not linked automatically?
|
||||
|
||||
|
||||
@@ -184,3 +184,17 @@ const text = ({ url, site }) => `Sign in to ${site}\n${url}\n\n`
|
||||
:::tip
|
||||
If you want to generate great looking email client compatible HTML with React, check out https://mjml.io
|
||||
:::
|
||||
|
||||
|
||||
## Customising the Verification Token
|
||||
|
||||
By default, we are generating a random verification token. You can define a `generateVerificationToken` method in your provider options if you want to override it:
|
||||
|
||||
```js title="pages/api/auth/[...nextauth].js"
|
||||
providers: [
|
||||
Providers.Email({
|
||||
async generateVerificationToken() {
|
||||
return "ABC123"
|
||||
}
|
||||
})
|
||||
],
|
||||
@@ -11,6 +11,8 @@ https://dev.twitch.tv/docs/authentication
|
||||
|
||||
https://dev.twitch.tv/console/apps
|
||||
|
||||
Add the following redirect URL into the console `http://<your-next-app-url>/api/auth/callback/twitch`
|
||||
|
||||
## Example
|
||||
|
||||
```js
|
||||
@@ -23,4 +25,4 @@ providers: [
|
||||
})
|
||||
]
|
||||
...
|
||||
```
|
||||
```
|
||||
|
||||
@@ -9,6 +9,10 @@ _These tutorials are contributed by the community and hosted on this site._
|
||||
|
||||
_New submissions and edits are welcome!_
|
||||
|
||||
### [Refresh Token Rotation](tutorials/refresh-token-rotation)
|
||||
|
||||
How to implement refresh token rotation.
|
||||
|
||||
### [Securing pages and API routes](tutorials/securing-pages-and-api-routes)
|
||||
|
||||
How to restrict access to pages and API routes.
|
||||
@@ -67,7 +71,6 @@ This example shows how to implement a fullstack app in TypeScript with Next.js u
|
||||
|
||||
This `dev.to` tutorial walks one through adding NextAuth.js to an existing project. Including setting up the OAuth client id and secret, adding the API routes for authentication, protecting pages and api routes behind that authentication, etc.
|
||||
|
||||
|
||||
### [Adding Sign in With Apple Next JS](https://thesiddd.com/blog/apple-auth)
|
||||
|
||||
This tutorial walks step by step on how to get Sign In with Apple working (both locally and on a deployed website) using NextAuth.js.
|
||||
|
||||
139
www/docs/tutorials/refresh-token-rotation.md
Normal file
139
www/docs/tutorials/refresh-token-rotation.md
Normal file
@@ -0,0 +1,139 @@
|
||||
---
|
||||
id: refresh-token-rotation
|
||||
title: Refresh Token Rotation
|
||||
---
|
||||
|
||||
While NextAuth.js doesn't automatically handle access token rotation for OAuth providers yet, this functionality can be implemented using [callbacks](https://next-auth.js.org/configuration/callbacks).
|
||||
|
||||
## Source Code
|
||||
|
||||
_A working example can be accessed [here](https://github.com/lawrencecchen/next-auth-refresh-tokens)._
|
||||
|
||||
## Implementation
|
||||
|
||||
### Server Side
|
||||
|
||||
Using a [JWT callback](https://next-auth.js.org/configuration/callbacks#jwt-callback) and a [session callback](https://next-auth.js.org/configuration/callbacks#session-callback), we can persist OAuth tokens and refresh them when they expire.
|
||||
|
||||
Below is a sample implementation using Google's Identity Provider. Please note that the OAuth 2.0 request in the `refreshAccessToken()` function will vary between different providers, but the core logic should remain similar.
|
||||
|
||||
```js title="pages/auth/[...nextauth.js]"
|
||||
import NextAuth from "next-auth";
|
||||
import Providers from "next-auth/providers";
|
||||
|
||||
const GOOGLE_AUTHORIZATION_URL =
|
||||
"https://accounts.google.com/o/oauth2/v2/auth?" +
|
||||
new URLSearchParams({
|
||||
prompt: "consent",
|
||||
access_type: "offline",
|
||||
response_type: "code",
|
||||
});
|
||||
|
||||
/**
|
||||
* Takes a token, and returns a new token with updated
|
||||
* `accessToken` and `accessTokenExpires`. If an error occurs,
|
||||
* returns the old token and an error property
|
||||
*/
|
||||
async function refreshAccessToken(token) {
|
||||
try {
|
||||
const url =
|
||||
"https://oauth2.googleapis.com/token?" +
|
||||
new URLSearchParams({
|
||||
client_id: process.env.GOOGLE_CLIENT_ID,
|
||||
client_secret: process.env.GOOGLE_CLIENT_SECRET,
|
||||
grant_type: "refresh_token",
|
||||
refresh_token: token.refreshToken,
|
||||
});
|
||||
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
method: "POST",
|
||||
});
|
||||
|
||||
const refreshedTokens = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw refreshedTokens;
|
||||
}
|
||||
|
||||
return {
|
||||
...token,
|
||||
accessToken: refreshedTokens.access_token,
|
||||
accessTokenExpires: Date.now() + refreshedTokens.expires_in * 1000,
|
||||
refreshToken: refreshedTokens.refresh_token ?? token.refreshToken, // Fall back to old refresh token
|
||||
};
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
|
||||
return {
|
||||
...token,
|
||||
error: "RefreshAccessTokenError",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export default NextAuth({
|
||||
providers: [
|
||||
Providers.Google({
|
||||
clientId: process.env.GOOGLE_CLIENT_ID,
|
||||
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
|
||||
authorizationUrl: GOOGLE_AUTHORIZATION_URL,
|
||||
}),
|
||||
],
|
||||
callbacks: {
|
||||
async jwt(token, user, account) {
|
||||
// Initial sign in
|
||||
if (account && user) {
|
||||
return {
|
||||
accessToken: account.accessToken,
|
||||
accessTokenExpires: Date.now() + account.expires_in * 1000,
|
||||
refreshToken: account.refresh_token,
|
||||
user,
|
||||
};
|
||||
}
|
||||
|
||||
// Return previous token if the access token has not expired yet
|
||||
if (Date.now() < token.accessTokenExpires) {
|
||||
return token;
|
||||
}
|
||||
|
||||
// Access token has expired, try to update it
|
||||
return refreshAccessToken(token);
|
||||
},
|
||||
async session(session, token) {
|
||||
if (token) {
|
||||
session.user = token.user;
|
||||
session.accessToken = token.accessToken;
|
||||
session.error = token.error;
|
||||
}
|
||||
|
||||
return session;
|
||||
},
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Client Side
|
||||
|
||||
The `RefreshAccessTokenError` error that is caught in the `refreshAccessToken()` method is passed all the way to the client. This means that you can direct the user to the sign in flow if we cannot refresh their token.
|
||||
|
||||
We can handle this functionality as a side effect:
|
||||
|
||||
```js title="pages/auth/[...nextauth.js]"
|
||||
import { signIn, useSession } from "next-auth/client";
|
||||
import { useEffect } from "react";
|
||||
|
||||
const HomePage() {
|
||||
const [session] = useSession();
|
||||
|
||||
useEffect(() => {
|
||||
if (session?.error === "RefreshAccessTokenError") {
|
||||
signIn(); // Force sign in to hopefully resolve error
|
||||
}
|
||||
}, [session]);
|
||||
|
||||
return (...)
|
||||
}
|
||||
```
|
||||
Reference in New Issue
Block a user