Skip to content

Commit ded6afa

Browse files
committed
Add comprehensive documentation for JwtSession including getting started guide, configuration options, API reference, RSA keys usage, security best practices, and internal implementation details.
1 parent 26f06fa commit ded6afa

File tree

7 files changed

+644
-57
lines changed

7 files changed

+644
-57
lines changed

README.md

Lines changed: 19 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,18 @@
66
[![GitHub license](https://img.shields.io/github/license/byjg/jwt-session.svg)](https://opensource.byjg.com/opensource/licensing.html)
77
[![GitHub release](https://img.shields.io/github/release/byjg/jwt-session.svg)](https://github.com/byjg/jwt-session/releases/)
88

9-
JwtSession is a PHP session replacement. Instead of use FileSystem, just use JWT TOKEN.
9+
JwtSession is a PHP session replacement. Instead of use FileSystem, just use JWT TOKEN.
1010
The implementation following the SessionHandlerInterface.
1111

12+
## Documentation
13+
14+
- [Getting Started](docs/getting-started.md) - Installation, basic usage, and motivation
15+
- [Configuration](docs/configuration.md) - Session timeout, contexts, cookies, and all configuration options
16+
- [RSA Keys](docs/rsa-keys.md) - Using RSA private/public keys for enhanced security
17+
- [How It Works](docs/how-it-works.md) - Architecture and internal implementation details
18+
- [Security](docs/security.md) - Security considerations and best practices
19+
- [API Reference](docs/api-reference.md) - Complete API documentation for all classes and methods
20+
1221
# How to use:
1322

1423
Before the session_start() use the command:
@@ -24,38 +33,19 @@ session_set_save_handler($handler, true);
2433

2534
Now, all your `$_SESSION` variable will be saved directly to a JWT Token!!
2635

27-
## Secret key
28-
Make sure that you are providing a base64url encoded key.
29-
30-
# Motivation
31-
32-
The default PHP Session does not work in different servers using round robin or other algorithms.
33-
This occurs because PHP Session are saved by default in the file system.
34-
35-
There are implementations can save the session to REDIS or MEMCACHED, for example.
36-
But this requires to you create a new server to store this session and creates a single point of failure.
37-
To avoid this you have to create REDIS/MEMCACHED clusters.
38-
39-
But if you save the session into JWT Token you do not need to create a new server.
40-
Just to use.
41-
42-
You can read more in this Codementor's article:
43-
[Using JSON Web Token (JWT) as a PHP Session](https://www.codementor.io/byjg/using-json-web-token-jwt-as-a-php-session-axeuqbg1m)
44-
45-
# Security Information
36+
**Note:** Make sure that you are providing a base64url encoded key.
4637

47-
The JWT Token cannot be changed, but it can be read.
48-
This implementation save the JWT into a client cookie.
49-
Because of this _**do not** store in the JWT Token sensible data like passwords_.
38+
For more details on motivation, security considerations, and best practices, see the [Documentation](#documentation) section above.
5039

5140
# Install
5241

5342
```
5443
composer require "byjg/jwt-session"
5544
```
5645

57-
58-
# Setting the validity of JWT Token
46+
# Configuration Examples
47+
48+
## Setting the validity of JWT Token
5949

6050
```php
6151
<?php
@@ -67,7 +57,7 @@ $handler = new \ByJG\Session\JwtSession($sessionConfig);
6757
session_set_save_handler($handler, true);
6858
```
6959

70-
# Setting the different Session Contexts
60+
## Setting different Session Contexts
7161

7262
```php
7363
<?php
@@ -79,30 +69,9 @@ $handler = new \ByJG\Session\JwtSession($sessionConfig);
7969
session_set_save_handler($handler, true);
8070
```
8171

82-
# Create the handler and replace the session handler
83-
84-
```php
85-
<?php
86-
$sessionConfig = (new \ByJG\Session\SessionConfig('your.domain.com'))
87-
->withSecret('your super base64url encoded secret key')
88-
->replaceSessionHandler();
89-
90-
$handler = new \ByJG\Session\JwtSession($sessionConfig);
91-
```
92-
93-
# Specify cookie domain
94-
95-
```php
96-
<?php
97-
$sessionConfig = (new \ByJG\Session\SessionConfig('your.domain.com'))
98-
->withSecret('your super base64url encoded secret key')
99-
->withCookie('.mydomain.com', '/')
100-
->replaceSessionHandler();
101-
102-
$handler = new \ByJG\Session\JwtSession($sessionConfig);
103-
```
72+
For complete configuration options including cookie domains and automatic session handler replacement, see [Configuration](docs/configuration.md).
10473

105-
# Uses RSA Private/Public Keys
74+
## Using RSA Private/Public Keys
10675

10776
```php
10877
<?php
@@ -155,14 +124,7 @@ $sessionConfig = (new \ByJG\Session\SessionConfig('example.com'))
155124
$handler = new \ByJG\Session\JwtSession($sessionConfig);
156125
```
157126

158-
If you want to know more details about how to create RSA Public/Private Keys access:
159-
https://github.com/byjg/jwt-wrapper
160-
161-
162-
# How it works
163-
164-
We store a cookie named `AUTH_BEARER_` followed by the context name with the session name. The PHPSESSID cookie is still created because
165-
PHP create it by default but we do not use it;
127+
For more details about RSA keys and how to generate them, see [RSA Keys](docs/rsa-keys.md) and https://github.com/byjg/jwt-wrapper
166128

167129

168130
## Dependencies

docs/api-reference.md

Lines changed: 272 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,272 @@
1+
---
2+
sidebar_position: 6
3+
---
4+
5+
# API Reference
6+
7+
## Classes
8+
9+
### `ByJG\Session\JwtSession`
10+
11+
Implements PHP's `SessionHandlerInterface` to provide JWT-based session storage.
12+
13+
#### Constants
14+
15+
- **`COOKIE_PREFIX`** = `"AUTH_BEARER_"`
16+
Prefix for the session cookie name.
17+
18+
#### Constructor
19+
20+
```php
21+
public function __construct(SessionConfig $sessionConfig)
22+
```
23+
24+
**Parameters:**
25+
- `$sessionConfig` (SessionConfig): Configuration object for the JWT session
26+
27+
**Throws:**
28+
- `JwtSessionException`: If SessionConfig instance is invalid or session already started
29+
30+
#### SessionHandlerInterface Methods
31+
32+
##### `open(string $path, string $name): bool`
33+
34+
Initialize the session (no-op in JWT implementation).
35+
36+
##### `close(): bool`
37+
38+
Close the session (no-op in JWT implementation).
39+
40+
##### `read(string $id): string`
41+
42+
Read session data from JWT cookie.
43+
44+
**Parameters:**
45+
- `$id` (string): Session ID (not used in JWT implementation)
46+
47+
**Returns:** Serialized session data string, or empty string if no session exists
48+
49+
##### `write(string $id, string $data): bool`
50+
51+
Write session data to JWT cookie.
52+
53+
**Parameters:**
54+
- `$id` (string): Session ID (not used in JWT implementation)
55+
- `$data` (string): Serialized session data from PHP
56+
57+
**Returns:** true on success
58+
59+
**Throws:**
60+
- `JwtWrapperException`: If JWT token generation fails
61+
62+
##### `destroy(string $id): bool`
63+
64+
Destroy the session by clearing the JWT cookie.
65+
66+
**Parameters:**
67+
- `$id` (string): Session ID to destroy
68+
69+
**Returns:** true on success
70+
71+
##### `gc(int $max_lifetime): int|false`
72+
73+
Garbage collection (no-op in JWT implementation as tokens are self-expiring).
74+
75+
**Parameters:**
76+
- `$max_lifetime` (int): Maximum session lifetime
77+
78+
**Returns:** true
79+
80+
#### Public Helper Methods
81+
82+
##### `serializeSessionData(array $array): string`
83+
84+
Manually serialize session data into PHP session format.
85+
86+
**Parameters:**
87+
- `$array` (array): Associative array of session data
88+
89+
**Returns:** Serialized string in PHP session format
90+
91+
##### `unSerializeSessionData(string $session_data): array`
92+
93+
Parse PHP session serialized data back into an array.
94+
95+
**Parameters:**
96+
- `$session_data` (string): Serialized session data
97+
98+
**Returns:** Associative array of session variables
99+
100+
**Throws:**
101+
- `JwtSessionException`: If session data format is invalid
102+
103+
---
104+
105+
### `ByJG\Session\SessionConfig`
106+
107+
Configuration class for JWT sessions with fluent interface.
108+
109+
#### Constructor
110+
111+
```php
112+
public function __construct(string $serverName)
113+
```
114+
115+
**Parameters:**
116+
- `$serverName` (string): Server name/domain for JWT token
117+
118+
#### Configuration Methods
119+
120+
##### `withSecret(string $secret): static`
121+
122+
Set the secret key for JWT encoding/decoding.
123+
124+
**Parameters:**
125+
- `$secret` (string): Base64url encoded secret key
126+
127+
**Returns:** Self for method chaining
128+
129+
##### `withRsaSecret(string $private, string $public): static`
130+
131+
Use RSA private/public keys for JWT encoding/decoding.
132+
133+
**Parameters:**
134+
- `$private` (string): RSA private key (PEM format)
135+
- `$public` (string): RSA public key (PEM format)
136+
137+
**Returns:** Self for method chaining
138+
139+
##### `withTimeoutMinutes(int $timeout): static`
140+
141+
Set JWT token validity in minutes.
142+
143+
**Parameters:**
144+
- `$timeout` (int): Timeout in minutes (default: 20)
145+
146+
**Returns:** Self for method chaining
147+
148+
##### `withTimeoutHours(int $timeout): static`
149+
150+
Set JWT token validity in hours.
151+
152+
**Parameters:**
153+
- `$timeout` (int): Timeout in hours
154+
155+
**Returns:** Self for method chaining
156+
157+
##### `withSessionContext(string $context): static`
158+
159+
Set custom session context name.
160+
161+
**Parameters:**
162+
- `$context` (string): Context name (default: 'default')
163+
164+
**Returns:** Self for method chaining
165+
166+
##### `withCookie(string $domain, string $path = '/'): static`
167+
168+
Configure cookie domain and path.
169+
170+
**Parameters:**
171+
- `$domain` (string): Cookie domain (e.g., '.example.com')
172+
- `$path` (string): Cookie path (default: '/')
173+
174+
**Returns:** Self for method chaining
175+
176+
##### `replaceSessionHandler(bool $startSession = true): static`
177+
178+
Configure automatic session handler replacement.
179+
180+
**Parameters:**
181+
- `$startSession` (bool): Whether to start session automatically (default: true)
182+
183+
**Returns:** Self for method chaining
184+
185+
#### Getter Methods
186+
187+
##### `getServerName(): string`
188+
189+
Get the configured server name.
190+
191+
##### `getSessionContext(): string`
192+
193+
Get the session context name.
194+
195+
##### `getTimeoutMinutes(): int`
196+
197+
Get the timeout in minutes.
198+
199+
##### `getCookieDomain(): ?string`
200+
201+
Get the cookie domain.
202+
203+
##### `getCookiePath(): string`
204+
205+
Get the cookie path.
206+
207+
##### `getKey(): ?JwtKeyInterface`
208+
209+
Get the JWT key interface instance.
210+
211+
##### `isReplaceSession(): bool`
212+
213+
Check if session handler replacement is configured.
214+
215+
##### `isStartSession(): bool`
216+
217+
Check if automatic session start is enabled.
218+
219+
---
220+
221+
### `ByJG\Session\JwtSessionException`
222+
223+
Exception class for JWT session errors.
224+
225+
**Extends:** `Exception`
226+
227+
**Use cases:**
228+
- Invalid SessionConfig provided
229+
- Session already started
230+
- Invalid serialized session data
231+
232+
## Example Usage
233+
234+
### Basic Implementation
235+
236+
```php
237+
<?php
238+
use ByJG\Session\SessionConfig;
239+
use ByJG\Session\JwtSession;
240+
241+
try {
242+
$config = (new SessionConfig('example.com'))
243+
->withSecret('your-base64url-encoded-secret')
244+
->withTimeoutMinutes(30)
245+
->withCookie('.example.com', '/');
246+
247+
$handler = new JwtSession($config);
248+
session_set_save_handler($handler, true);
249+
session_start();
250+
251+
// Use $_SESSION as normal
252+
$_SESSION['user_id'] = 123;
253+
254+
} catch (JwtSessionException $e) {
255+
// Handle exception
256+
error_log('Session error: ' . $e->getMessage());
257+
}
258+
```
259+
260+
### With Automatic Handler Replacement
261+
262+
```php
263+
<?php
264+
$config = (new SessionConfig('example.com'))
265+
->withSecret('your-base64url-encoded-secret')
266+
->replaceSessionHandler(true); // Automatically starts session
267+
268+
$handler = new JwtSession($config);
269+
270+
// Session is already started, use $_SESSION directly
271+
$_SESSION['user_id'] = 123;
272+
```

0 commit comments

Comments
 (0)