Skip to content

Commit f488c77

Browse files
jhoward1994pwizla
authored andcommitted
Add session management documentation (#2709)
* feat: add session management and authentication enhancements to CMS documentation * Move endpoints to U&P feature docs and rework related sections * Clean up configurations- and environment variables-related content * Fix typo in link * Clean up examples because they were mixing legacy and session management * Update LLMs-full.txt * Update docusaurus/docs/cms/configurations/admin-panel.md Co-authored-by: Jamie Howard <48524071+jhoward1994@users.noreply.github.com> * Remove useless/wrong values from env docs * Update docusaurus/docs/cms/features/users-permissions.md --------- Co-authored-by: Pierre Wizla <pwizla+github@gmail.com> Co-authored-by: Pierre Wizla <pwizla@users.noreply.github.com>
1 parent 2dfddb5 commit f488c77

File tree

6 files changed

+353
-25
lines changed

6 files changed

+353
-25
lines changed

docusaurus/docs/cms/api/rest.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ tags:
1616

1717
The REST API allows accessing the [content-types](/cms/backend-customization/models) through API endpoints. Strapi automatically creates [API endpoints](#endpoints) when a content-type is created. [API parameters](/cms/api/rest/parameters) can be used when querying API endpoints to refine the results.
1818

19-
This section of the documentation is for the REST API reference. We also have [guides](/cms/api/rest/guides/intro) available for specific use cases.
19+
This section of the documentation is for the REST API reference for content-types. We also have [guides](/cms/api/rest/guides/intro) available for specific use cases.
2020

2121
:::prerequisites
2222
All content types are private by default and need to be either made public or queries need to be authenticated with the proper permissions. See the [Quick Start Guide](/cms/quick-start#step-4-set-roles--permissions), the user guide for the [Users & Permissions feature](/cms/features/users-permissions#roles), and [API tokens configuration documentation](/cms/features/api-tokens) for more details.

docusaurus/docs/cms/backend-customization/examples/authentication.md

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,120 @@ const Login = () => {
145145
export default Login;
146146
```
147147

148+
## Enhanced Authentication with Session Management
149+
150+
The above example uses the traditional JWT approach. For enhanced security, you can enable session management mode in your Users & Permissions configuration, which provides shorter-lived access tokens and refresh token functionality.
151+
152+
### Configuration
153+
154+
First, enable session management in your `/config/plugins.js`:
155+
156+
```js title="/config/plugins.js"
157+
module.exports = ({ env }) => ({
158+
'users-permissions': {
159+
config: {
160+
jwtManagement: 'refresh',
161+
sessions: {
162+
accessTokenLifespan: 604800, // 1 week (default)
163+
maxRefreshTokenLifespan: 2592000, // 30 days
164+
idleRefreshTokenLifespan: 604800, // 7 days
165+
},
166+
},
167+
},
168+
});
169+
```
170+
171+
### Enhanced Login Component
172+
173+
Here's an updated login component that handles both JWT and refresh tokens:
174+
175+
```jsx title="/client/pages/auth/enhanced-login.js"
176+
import React, { useState } from 'react';
177+
import { useFormik } from 'formik';
178+
import { Button, Input } from '@nextui-org/react';
179+
import Layout from '@/components/layout';
180+
import { getStrapiURL } from '@/utils';
181+
182+
const EnhancedLogin = () => {
183+
const [isLoading, setIsLoading] = useState(false);
184+
185+
const { handleSubmit, handleChange } = useFormik({
186+
initialValues: {
187+
identifier: '',
188+
password: '',
189+
},
190+
onSubmit: async (values) => {
191+
setIsLoading(true);
192+
try {
193+
const res = await fetch(getStrapiURL('/auth/local'), {
194+
method: 'POST',
195+
headers: {
196+
'Content-Type': 'application/json',
197+
},
198+
body: JSON.stringify(values),
199+
});
200+
201+
const data = await res.json();
202+
203+
if (res.ok) {
204+
// Store both tokens (session management mode)
205+
if (data.refreshToken) {
206+
localStorage.setItem('accessToken', data.jwt);
207+
localStorage.setItem('refreshToken', data.refreshToken);
208+
} else {
209+
// Legacy mode - single JWT
210+
localStorage.setItem('token', data.jwt);
211+
}
212+
213+
// Redirect to protected area
214+
window.location.href = '/dashboard';
215+
} else {
216+
console.error('Login failed:', data.error);
217+
}
218+
} catch (error) {
219+
console.error('Login error:', error);
220+
} finally {
221+
setIsLoading(false);
222+
}
223+
},
224+
});
225+
226+
return (
227+
<Layout>
228+
<div className="h-full w-full flex justify-center items-center my-24">
229+
<form onSubmit={handleSubmit} className="flex flex-col gap-y-6 w-4/12">
230+
<h1 className="font-bold text-3xl mb-6">Enhanced Login</h1>
231+
<Input
232+
onChange={handleChange}
233+
type="email"
234+
name="identifier"
235+
label="Email"
236+
placeholder="Enter your email"
237+
/>
238+
<Input
239+
type="password"
240+
name="password"
241+
label="Password"
242+
placeholder="Enter your password"
243+
onChange={handleChange}
244+
/>
245+
<Button
246+
type="submit"
247+
className="bg-primary rounded-md text-muted"
248+
disabled={isLoading}
249+
>
250+
{isLoading ? 'Logging in...' : 'Login'}
251+
</Button>
252+
</form>
253+
</div>
254+
</Layout>
255+
);
256+
};
257+
258+
export default EnhancedLogin;
259+
```
260+
```
261+
148262
<br />
149263
150264
:::strapi What's next?

docusaurus/docs/cms/configurations/admin-panel.md

Lines changed: 68 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
title: Admin panel configuration
33
sidebar_label: Admin panel
44
displayed_sidebar: cmsSidebar
5-
toc_max_heading_level: 2
5+
toc_max_heading_level: 3
66
description: Strapi's admin panel offers a single entry point file for its configuration.
77
tags:
88
- admin panel
@@ -57,7 +57,7 @@ export default {
5757

5858
:::
5959

60-
## Admin panel server
60+
## Admin panel server
6161

6262
By default, Strapi's admin panel is exposed via `http://localhost:1337/admin`. For security reasons, the host, port, and path can be updated.
6363

@@ -204,7 +204,11 @@ For Strapi Cloud customers, the `auditLogs.retentionDays` value stored in the li
204204

205205
## Authentication
206206

207-
The authentication system, including [SSO configuration](/cms/configurations/guides/configure-sso), can be configured with the following parameters:
207+
The authentication system, including [SSO configuration](/cms/configurations/guides/configure-sso) and [session management](#session-management), can be configured with the following parameters:
208+
209+
### Basic authentication
210+
211+
To configure basic authentication, use the following parameters:
208212

209213
| Parameter | Description | Type | Default |
210214
|-----------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|-------------------------------------------------------------------------------------------------------------------------------------|
@@ -218,6 +222,43 @@ The authentication system, including [SSO configuration](/cms/configurations/gui
218222
| `auth.events.onConnectionSuccess` | Function called when an admin user log in successfully to the administration panel | function | `undefined` |
219223
| `auth.events.onConnectionError` | Function called when an admin user fails to log in to the administration panel | function | `undefined` |
220224

225+
Additional configuration parameters are available for [session management](#session-management).
226+
227+
### Session management
228+
229+
Admin authentication uses session management by default for enhanced security.
230+
231+
Session management provides enhanced security for authentication in Strapi applications by using short-lived access tokens paired with longer-lived refresh tokens. This approach reduces the risk of token theft and allows for more granular control over user sessions.
232+
233+
Strapi's session management system supports both admin panel authentication and Content API authentication through the [Users & Permissions feature](/cms/features/users-permissions). The system provides:
234+
235+
- Short-lived access tokens (typically 30 minutes) for API requests
236+
- Refresh tokens for obtaining new access tokens
237+
- Device-specific sessions for targeted logout
238+
- Configurable token lifespans for different security requirements
239+
240+
To configure session lifespans and behavior, use the following parameters:
241+
242+
| Parameter | Description | Type | Default |
243+
|-------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|-------------------------------------------------------------------------------------------------------------------------------------|
244+
| `auth.sessions` | Session management configuration | object | `{}` |
245+
| `auth.sessions.accessTokenLifespan` | Access token lifespan in seconds | number | `1800` (30 minutes) |
246+
| `auth.sessions.maxRefreshTokenLifespan` | Maximum refresh token lifespan in seconds | number | `2592000` (30 days, or legacy `expiresIn` value) |
247+
| `auth.sessions.idleRefreshTokenLifespan` | Idle refresh token timeout in seconds | number | `604800` (7 days) |
248+
| `auth.sessions.maxSessionLifespan` | Maximum session duration in seconds | number | `2592000` (30 days, or legacy `expiresIn` value) |
249+
| `auth.sessions.idleSessionLifespan` | Session idle timeout in seconds | number | `3600` (1 hour) |
250+
251+
### Cookie configuration
252+
253+
To configure HTTP cookies for admin authentication, use the following parameters:
254+
255+
| Parameter | Description | Type | Default |
256+
|-----------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|-------------------------------------------------------------------------------------------------------------------------------------|
257+
| `auth.cookie` | Cookie configuration for admin authentication | object | `{}` |
258+
| `auth.cookie.domain` | Cookie domain (inherits from server if not set) | string | `undefined` |
259+
| `auth.cookie.path` | Cookie path | string | `'/admin'` |
260+
| `auth.cookie.sameSite` | <ExternalLink to="https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Set-Cookie#samesitesamesite-value" text="SameSite cookie attribute"/> | string | `'lax'` |
261+
221262
## Feature flags
222263

223264
The feature flags can be configured with the following parameters:
@@ -365,6 +406,18 @@ module.exports = ({ env }) => ({
365406
expiresIn: '7d',
366407
},
367408
secret: env('ADMIN_JWT_SECRET', 'someSecretKey'),
409+
sessions: {
410+
accessTokenLifespan: 1800, // 30 minutes
411+
maxRefreshTokenLifespan: 2592000, // 30 days
412+
idleRefreshTokenLifespan: 604800, // 7 days
413+
maxSessionLifespan: 604800, // 7 days
414+
idleSessionLifespan: 3600, // 1 hour
415+
},
416+
cookie: {
417+
domain: env('ADMIN_COOKIE_DOMAIN'),
418+
path: '/admin',
419+
sameSite: 'lax',
420+
},
368421
},
369422
url: env('PUBLIC_ADMIN_URL', '/dashboard'),
370423
autoOpen: false,
@@ -423,6 +476,18 @@ export default ({ env }) => ({
423476
expiresIn: '7d',
424477
},
425478
secret: env('ADMIN_JWT_SECRET', 'someSecretKey'),
479+
sessions: {
480+
accessTokenLifespan: 1800, // 30 minutes
481+
maxRefreshTokenLifespan: 2592000, // 30 days
482+
idleRefreshTokenLifespan: 604800, // 7 days
483+
maxSessionLifespan: 604800, // 7 days
484+
idleSessionLifespan: 3600, // 1 hour
485+
},
486+
cookie: {
487+
domain: env('ADMIN_COOKIE_DOMAIN'),
488+
path: '/admin',
489+
sameSite: 'lax',
490+
},
426491
},
427492
url: env('PUBLIC_ADMIN_URL', '/dashboard'),
428493
autoOpen: false,

docusaurus/docs/cms/configurations/environment.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,30 @@ Prefixing an environment variable name with `STRAPI_ADMIN_` exposes the variable
5656

5757
<SampleEnv />
5858

59+
Set these environment variables for secure authentication with [sessions management](/cms/features/users-permissions#jwt-management-modes) configuration:
60+
61+
```bash title=".env"
62+
# Admin authentication
63+
ADMIN_JWT_SECRET=your-admin-secret-key
64+
65+
# Cookie domain (optional)
66+
ADMIN_COOKIE_DOMAIN=yourdomain.com
67+
68+
# Users & Permissions JWT secret
69+
JWT_SECRET=your-content-api-secret-key
70+
71+
# Users & Permissions session management
72+
UP_JWT_MANAGEMENT=refresh # or 'legacy-support'
73+
UP_SESSIONS_ACCESS_TTL=604800 # 1 week in seconds
74+
UP_SESSIONS_MAX_REFRESH_TTL=2592000 # 30 days in seconds
75+
UP_SESSIONS_IDLE_REFRESH_TTL=604800 # 7 days in seconds
76+
UP_SESSIONS_HTTPONLY=false # true for HTTP-only cookies
77+
UP_SESSIONS_COOKIE_NAME=strapi_up_refresh
78+
UP_SESSIONS_COOKIE_SAMESITE=lax
79+
UP_SESSIONS_COOKIE_PATH=/
80+
UP_SESSIONS_COOKIE_SECURE=false # true in production
81+
```
82+
5983
## Environment configurations
6084

6185
Configurations can be created with the following naming and structure conventions: `./config/env/{environment}/{filename}`. This is useful when you need specific static configurations for specific environments and using environment variables is not the best solution.

0 commit comments

Comments
 (0)