|
24 | 24 | - [`beforeSessionSaved`](#beforesessionsaved) |
25 | 25 | - [`onCallback`](#oncallback) |
26 | 26 | - [Session configuration](#session-configuration) |
| 27 | +- [Cookie Configuration](#cookie-configuration) |
27 | 28 | - [Database sessions](#database-sessions) |
28 | 29 | - [Back-Channel Logout](#back-channel-logout) |
29 | 30 | - [Combining middleware](#combining-middleware) |
@@ -520,6 +521,65 @@ export async function middleware(request: NextRequest) { |
520 | 521 | } |
521 | 522 | ``` |
522 | 523 |
|
| 524 | +### Forcing Access Token Refresh |
| 525 | + |
| 526 | +In some scenarios, you might need to explicitly force the refresh of an access token, even if it hasn't expired yet. This can be useful if, for example, the user's permissions or scopes have changed and you need to ensure the application has the latest token reflecting these changes. |
| 527 | + |
| 528 | +The `getAccessToken` method provides an option to force this refresh. |
| 529 | + |
| 530 | +**App Router (Server Components, Route Handlers, Server Actions):** |
| 531 | + |
| 532 | +When calling `getAccessToken` without request and response objects, you can pass an options object as the first argument. Set the `refresh` property to `true` to force a token refresh. |
| 533 | + |
| 534 | +```typescript |
| 535 | +// app/api/my-api/route.ts |
| 536 | +import { getAccessToken } from '@auth0/nextjs-auth0'; |
| 537 | + |
| 538 | +export async function GET() { |
| 539 | + try { |
| 540 | + // Force a refresh of the access token |
| 541 | + const { token, expiresAt } = await getAccessToken({ refresh: true }); |
| 542 | + |
| 543 | + // Use the refreshed token |
| 544 | + // ... |
| 545 | + } catch (error) { |
| 546 | + console.error('Error getting access token:', error); |
| 547 | + return Response.json({ error: 'Failed to get access token' }, { status: 500 }); |
| 548 | + } |
| 549 | +} |
| 550 | +``` |
| 551 | + |
| 552 | +**Pages Router (getServerSideProps, API Routes):** |
| 553 | + |
| 554 | +When calling `getAccessToken` with request and response objects (from `getServerSideProps` context or an API route), the options object is passed as the third argument. |
| 555 | + |
| 556 | +```typescript |
| 557 | +// pages/api/my-pages-api.ts |
| 558 | +import { getAccessToken, withApiAuthRequired } from '@auth0/nextjs-auth0'; |
| 559 | +import type { NextApiRequest, NextApiResponse } from 'next'; |
| 560 | + |
| 561 | +export default withApiAuthRequired(async function handler( |
| 562 | + req: NextApiRequest, |
| 563 | + res: NextApiResponse |
| 564 | +) { |
| 565 | + try { |
| 566 | + // Force a refresh of the access token |
| 567 | + const { token, expiresAt } = await getAccessToken(req, res, { |
| 568 | + refresh: true |
| 569 | + }); |
| 570 | + |
| 571 | + // Use the refreshed token |
| 572 | + // ... |
| 573 | + } catch (error: any) { |
| 574 | + console.error('Error getting access token:', error); |
| 575 | + res.status(error.status || 500).json({ error: error.message }); |
| 576 | + } |
| 577 | +}); |
| 578 | +``` |
| 579 | + |
| 580 | +By setting `{ refresh: true }`, you instruct the SDK to bypass the standard expiration check and request a new access token from the identity provider using the refresh token (if available and valid). The new token set (including the potentially updated access token, refresh token, and expiration time) will be saved back into the session automatically. |
| 581 | +This will in turn, update the `access_token`, `id_token` and `expires_at` fields of `tokenset` in the session. |
| 582 | + |
523 | 583 | ## `<Auth0Provider />` |
524 | 584 |
|
525 | 585 | ### Passing an initial user from the server |
@@ -626,6 +686,67 @@ export const auth0 = new Auth0Client({ |
626 | 686 | | absoluteDuration | `number` | The absolute duration after which the session will expire. The value must be specified in seconds. Default: `3 days`. | |
627 | 687 | | inactivityDuration | `number` | The duration of inactivity after which the session will expire. The value must be specified in seconds. Default: `1 day`. | |
628 | 688 |
|
| 689 | +## Cookie Configuration |
| 690 | + |
| 691 | +You can configure the session cookie attributes either through environment variables or directly in the SDK initialization. |
| 692 | + |
| 693 | +**1. Using Environment Variables:** |
| 694 | + |
| 695 | +Set the desired environment variables in your `.env.local` file or your deployment environment: |
| 696 | + |
| 697 | +``` |
| 698 | +# .env.local |
| 699 | +# ... other variables ... |
| 700 | +
|
| 701 | +# Cookie Options |
| 702 | +AUTH0_COOKIE_DOMAIN='.example.com' # Set cookie for subdomains |
| 703 | +AUTH0_COOKIE_PATH='/app' # Limit cookie to /app path |
| 704 | +AUTH0_COOKIE_TRANSIENT=true # Make cookie transient (session-only) |
| 705 | +AUTH0_COOKIE_SECURE=true # Recommended for production |
| 706 | +AUTH0_COOKIE_SAME_SITE='Lax' |
| 707 | +``` |
| 708 | + |
| 709 | +The SDK will automatically pick up these values. Note that `httpOnly` is always set to `true` for security reasons and cannot be configured. |
| 710 | + |
| 711 | +**2. Using `Auth0ClientOptions`:** |
| 712 | + |
| 713 | +Configure the options directly when initializing the client: |
| 714 | + |
| 715 | +```typescript |
| 716 | +import { Auth0Client } from "@auth0/nextjs-auth0/server" |
| 717 | + |
| 718 | +export const auth0 = new Auth0Client({ |
| 719 | + session: { |
| 720 | + cookie: { |
| 721 | + domain: '.example.com', |
| 722 | + path: '/app', |
| 723 | + transient: true, |
| 724 | + // httpOnly is always true and cannot be configured |
| 725 | + secure: process.env.NODE_ENV === 'production', |
| 726 | + sameSite: 'Lax', |
| 727 | + // name: 'appSession', // Optional: custom cookie name, defaults to '__session' |
| 728 | + }, |
| 729 | + // ... other session options like absoluteDuration ... |
| 730 | + }, |
| 731 | + // ... other client options ... |
| 732 | +}); |
| 733 | +``` |
| 734 | + |
| 735 | +**Session Cookie Options:** |
| 736 | + |
| 737 | +* `domain` (String): Specifies the `Domain` attribute. |
| 738 | +* `path` (String): Specifies the `Path` attribute. Defaults to `/`. |
| 739 | +* `transient` (Boolean): If `true`, the `maxAge` attribute is omitted, making it a session cookie. Defaults to `false`. |
| 740 | +* `secure` (Boolean): Specifies the `Secure` attribute. Defaults to `false` (or `true` if `AUTH0_COOKIE_SECURE=true` is set). |
| 741 | +* `sameSite` ('Lax' | 'Strict' | 'None'): Specifies the `SameSite` attribute. Defaults to `Lax` (or the value of `AUTH0_COOKIE_SAME_SITE`). |
| 742 | +* `name` (String): The name of the session cookie. Defaults to `__session`. |
| 743 | + |
| 744 | +> [!INFO] |
| 745 | +> Options provided directly in `Auth0ClientOptions` take precedence over environment variables. The `httpOnly` attribute is always `true` regardless of configuration. |
| 746 | +
|
| 747 | +> [!INFO] |
| 748 | +> The `httpOnly` attribute for the session cookie is always set to `true` for security reasons and cannot be configured via options or environment variables. |
| 749 | +
|
629 | 750 | ## Database sessions |
630 | 751 |
|
631 | 752 | By default, the user's sessions are stored in encrypted cookies. You may choose to persist the sessions in your data store of choice. |
|
0 commit comments