Skip to content

Commit 6f31d19

Browse files
authored
Merge pull request #11 from byjg/2.0.0
Release 2.0.0
2 parents cadf6d7 + 6d01a12 commit 6f31d19

File tree

11 files changed

+361
-64
lines changed

11 files changed

+361
-64
lines changed

README.md

Lines changed: 91 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,10 @@ Before the session_start() use the command:
1313

1414
```php
1515
<?php
16-
$handler = new \ByJG\Session\JwtSession('your.domain.com', 'your super secret key');
16+
$sessionConfig = (new \ByJG\Session\SessionConfig('your.domain.com'))
17+
->withSecret('your super secret key');
18+
19+
$handler = new \ByJG\Session\JwtSession($sessionConfig);
1720
session_set_save_handler($handler, true);
1821
```
1922

@@ -34,7 +37,7 @@ Just to use.
3437
You can read more in this Codementor's article:
3538
[Using JSON Web Token (JWT) as a PHP Session](https://www.codementor.io/byjg/using-json-web-token-jwt-as-a-php-session-axeuqbg1m)
3639

37-
## Security Information
40+
# Security Information
3841

3942
The JWT Token cannot be changed, but it can be read.
4043
This implementation save the JWT into a client cookie.
@@ -43,47 +46,119 @@ Because of this _**do not** store in the JWT Token sensible data like passwords_
4346
# Install
4447

4548
```
46-
composer require "byjg/jwt-session=1.0.*"
49+
composer require "byjg/jwt-session=2.0.*"
4750
```
4851

49-
# Customizations
5052

51-
## Setting the validity of JWT Token
53+
# Setting the validity of JWT Token
5254

5355
```php
5456
<?php
55-
// Setting to 50 minutes
56-
$handler = new \ByJG\Session\JwtSession('your.domain.com', 'your super secret key', 50);
57+
$sessionConfig = (new \ByJG\Session\SessionConfig('your.domain.com'))
58+
->withSecret('your super secret key')
59+
->withTimeoutMinutes(60); // You can use withTimeoutHours(1)
60+
61+
$handler = new \ByJG\Session\JwtSession($sessionConfig);
5762
session_set_save_handler($handler, true);
5863
```
5964

60-
## Setting the different Session Contexts
65+
# Setting the different Session Contexts
6166

6267
```php
6368
<?php
64-
$handler = new \ByJG\Session\JwtSession('your.domain.com', 'your super secret key', 20, 'MYCONTEXT');
69+
$sessionConfig = (new \ByJG\Session\SessionConfig('your.domain.com'))
70+
->withSecret('your super secret key')
71+
->withSessionContext('MYCONTEXT');
72+
73+
$handler = new \ByJG\Session\JwtSession($sessionConfig);
6574
session_set_save_handler($handler, true);
6675
```
6776

68-
## Create the handler and replace the session handler
77+
# Create the handler and replace the session handler
78+
79+
```php
80+
<?php
81+
$sessionConfig = (new \ByJG\Session\SessionConfig('your.domain.com'))
82+
->withSecret('your super secret key')
83+
->replaceSessionHandler();
84+
85+
$handler = new \ByJG\Session\JwtSession($sessionConfig);
86+
```
87+
88+
# Specify cookie domain
6989

7090
```php
7191
<?php
72-
$handler = new \ByJG\Session\JwtSession('your.domain.com', 'your super secret key');
73-
$handler->replaceSessionHandler(true);
92+
$sessionConfig = (new \ByJG\Session\SessionConfig('your.domain.com'))
93+
->withSecret('your super secret key')
94+
->withCookie('.mydomain.com', '/')
95+
->replaceSessionHandler();
96+
97+
$handler = new \ByJG\Session\JwtSession($sessionConfig);
7498
```
7599

76-
## Create the handler and replace the session handler, specifying cookie domain valid for all subdomains of mydomain.com
100+
# Uses RSA Private/Public Keys
77101

78102
```php
79103
<?php
80-
$handler = new \ByJG\Session\JwtSession('your.domain.com', 'your super secret key', null, null, '.mydomain.com');
81-
$handler->replaceSessionHandler(true);
104+
$secret = <<<PRIVATE
105+
-----BEGIN RSA PRIVATE KEY-----
106+
MIIEpQIBAAKCAQEA5PMdWRa+rUJmg6QMNAPIXa+BJVN7W0vxPN3WTK/OIv5gxgmj
107+
2inHGGc6f90TW/to948LnqGtcD3CD9KsI55MubafwBYjcds1o9opZ0vYwwdIV80c
108+
OVZX1IUZFTbnyyKcXeFmKt49A52haCiy4iNxcRK38tOCApjZySx/NzMDeaXuWe+1
109+
nd3pbgYa/I8MkECa5EyabhZJPJo9fGoSZIklNnyq4TfAUSwl+KN/zjj3CXad1oDT
110+
7XDDgMJDUu/Vxs7h3CQI9zILSYcL9zwttbLnJW1WcLlAAIaAfABtSZboznsStMnY
111+
to01wVknXKyERF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
127+
+jbTYp3Kk/vjKsQwfj/rJM+oRu3eF9qo5dbxT6btI++zVGV7lbEOFN6Sx30EV6gT
128+
bwKkZXkCgYEAnEtN43xL8bRFybMc1ZJErjc0VocnoQxCHm7LuAtLOEUw6CwwFj9Q
129+
GOl+GViVuDHUNQvURLn+6gg4tAemYlob912xIPaU44+lZzTMHBOJBGMJKi8WogKi
130+
V5+cz9l31uuAgNfjL63jZPaAzKs8Zx6R3O5RuezympwijCIGWILbO2Q=
131+
-----END RSA PRIVATE KEY-----
132+
PRIVATE;
133+
134+
$public = <<<PUBLIC
135+
-----BEGIN PUBLIC KEY-----
136+
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5PMdWRa+rUJmg6QMNAPI
137+
Xa+BJVN7W0vxPN3WTK/OIv5gxgmj2inHGGc6f90TW/to948LnqGtcD3CD9KsI55M
138+
ubafwBYjcds1o9opZ0vYwwdIV80cOVZX1IUZFTbnyyKcXeFmKt49A52haCiy4iNx
139+
cRK38tOCApjZySx/NzMDeaXuWe+1nd3pbgYa/I8MkECa5EyabhZJPJo9fGoSZIkl
140+
Nnyq4TfAUSwl+KN/zjj3CXad1oDT7XDDgMJDUu/Vxs7h3CQI9zILSYcL9zwttbLn
141+
JW1WcLlAAIaAfABtSZboznsStMnYto01wVknXKyERFs7FLHYqKQANIvRhFTptseh
142+
owIDAQAB
143+
-----END PUBLIC KEY-----
144+
PUBLIC;
145+
146+
$sessionConfig = (new \ByJG\Session\SessionConfig('example.com'))
147+
->withRsaSecret($secret, $public)
148+
->replaceSessionHandler();
149+
150+
$handler = new \ByJG\Session\JwtSession($sessionConfig);
82151
```
83152

84-
## How it works
153+
If you want to know more details about how to create RSA Public/Private Keys access:
154+
https://github.com/byjg/jwt-wrapper
155+
156+
157+
# How it works
85158

86159
We store a cookie named AUTH_BEARER_<context name> with the session name. The PHPSESSID cookie is still created because
87160
PHP create it by default but we do not use it;
88161

89162

163+
----
164+
[Open source ByJG](http://opensource.byjg.com)

_config.yml

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,13 +41,26 @@ social:
4141
hash: opensourcebyjg
4242
account:
4343
facebook:
44-
enabled: false
44+
enabled: true
45+
url: https://opensource.byjg.com/
4546
profileUrl:
4647

48+
author:
49+
twitter: byjg
50+
51+
twitter:
52+
card: summary
53+
username: byjg
54+
55+
logo: https://opensource.byjg.com/images/logo_byjg.png
56+
4757
analytics:
4858
google: UA-130014324-1
4959

60+
plugins:
61+
- jekyll-seo-tag
62+
5063
# Build settings
5164
markdown: kramdown
52-
remote_theme: allejo/jekyll-docs-theme
65+
remote_theme: byjg/jekyll-docs-theme
5366

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
"prefer-stable": true,
1717
"require": {
1818
"php": ">=5.6.0",
19-
"byjg/jwt-wrapper": "1.0.*"
19+
"byjg/jwt-wrapper": "2.0.*"
2020
},
2121
"require-dev": {
2222
"phpunit/phpunit": ">=5.7"

src/JwtSession.php

Lines changed: 49 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -9,48 +9,45 @@ class JwtSession implements SessionHandlerInterface
99
{
1010
const COOKIE_PREFIX = "AUTH_BEARER_";
1111

12-
protected $serverName;
13-
14-
protected $secretKey;
15-
16-
protected $timeOutMinutes;
17-
18-
protected $suffix = "default";
19-
20-
protected $cookieDomain;
21-
22-
protected $path = "/";
12+
/**
13+
* @var SessionConfig
14+
*/
15+
protected $sessionConfig;
2316

2417
/**
2518
* JwtSession constructor.
2619
*
27-
* @param $serverName
28-
* @param $secretKey
29-
* @param int $timeOutMinutes
20+
* @param $sessionConfig
21+
* @throws JwtSessionException
3022
*/
31-
public function __construct($serverName, $secretKey, $timeOutMinutes = null, $sessionContext = null, $cookieDomain = null, $path = "/")
23+
public function __construct($sessionConfig)
3224
{
33-
$this->serverName = $serverName;
34-
$this->secretKey = $secretKey;
35-
$this->timeOutMinutes = $timeOutMinutes ?: 20;
36-
$this->suffix = $sessionContext ?: 'default';
37-
$this->cookieDomain = $cookieDomain;
38-
$this->path = "/";
25+
ini_set("session.use_cookies", 0);
26+
27+
if (!($sessionConfig instanceof SessionConfig)) {
28+
throw new JwtSessionException('Required SessionConfig instance');
29+
}
30+
31+
$this->sessionConfig = $sessionConfig;
32+
33+
if ($this->sessionConfig->isReplaceSession()) {
34+
$this->replaceSessionHandler();
35+
}
3936
}
4037

4138
/**
4239
* @param bool $startSession
4340
* @throws JwtSessionException
4441
*/
45-
public function replaceSessionHandler($startSession = true)
42+
protected function replaceSessionHandler()
4643
{
4744
if (session_status() != PHP_SESSION_NONE) {
4845
throw new JwtSessionException('Session already started!');
4946
}
5047

5148
session_set_save_handler($this, true);
5249

53-
if ($startSession) {
50+
if ($this->sessionConfig->isStartSession()) {
5451
ob_start();
5552
session_start();
5653
}
@@ -86,11 +83,11 @@ public function destroy($session_id)
8683
{
8784
if (!headers_sent()) {
8885
setcookie(
89-
self::COOKIE_PREFIX . $this->suffix,
86+
self::COOKIE_PREFIX . $this->sessionConfig->getSessionContext(),
9087
null,
9188
(time()-3000),
92-
$this->path,
93-
$this->cookieDomain
89+
$this->sessionConfig->getCookiePath(),
90+
$this->sessionConfig->getCookieDomain()
9491
);
9592
}
9693

@@ -148,9 +145,16 @@ public function open($save_path, $name)
148145
public function read($session_id)
149146
{
150147
try {
151-
if (isset($_COOKIE[self::COOKIE_PREFIX . $this->suffix])) {
152-
$jwt = new JwtWrapper($this->serverName, $this->secretKey);
153-
$data = $jwt->extractData($_COOKIE[self::COOKIE_PREFIX . $this->suffix]);
148+
if (isset($_COOKIE[self::COOKIE_PREFIX . $this->sessionConfig->getSessionContext()])) {
149+
$jwt = new JwtWrapper(
150+
$this->sessionConfig->getServerName(),
151+
$this->sessionConfig->getKey()
152+
);
153+
$data = $jwt->extractData($_COOKIE[self::COOKIE_PREFIX . $this->sessionConfig->getSessionContext()]);
154+
155+
if (empty($data->data)) {
156+
return '';
157+
}
154158

155159
return $data->data;
156160
}
@@ -176,26 +180,30 @@ public function read($session_id)
176180
* The return value (usually TRUE on success, FALSE on failure).
177181
* Note this value is returned internally to PHP for processing.
178182
* </p>
183+
* @throws \ByJG\Util\JwtWrapperException
179184
* @since 5.4.0
180185
*/
181186
public function write($session_id, $session_data)
182187
{
183-
$jwt = new JwtWrapper($this->serverName, $this->secretKey);
184-
$data = $jwt->createJwtData($session_data, $this->timeOutMinutes * 60);
188+
$jwt = new JwtWrapper(
189+
$this->sessionConfig->getServerName(),
190+
$this->sessionConfig->getKey()
191+
);
192+
$data = $jwt->createJwtData($session_data, $this->sessionConfig->getTimeoutMinutes() * 60);
185193
$token = $jwt->generateToken($data);
186194

187195
if (!headers_sent()) {
188196
setcookie(
189-
self::COOKIE_PREFIX . $this->suffix,
197+
self::COOKIE_PREFIX . $this->sessionConfig->getSessionContext(),
190198
$token,
191-
(time()+$this->timeOutMinutes*60) ,
192-
$this->path,
193-
$this->cookieDomain,
199+
(time()+$this->sessionConfig->getTimeoutMinutes()*60) ,
200+
$this->sessionConfig->getCookiePath(),
201+
$this->sessionConfig->getCookieDomain(),
194202
false,
195203
true
196204
);
197205
if (defined("SETCOOKIE_FORTEST")) {
198-
$_COOKIE[self::COOKIE_PREFIX . $this->suffix] = $token;
206+
$_COOKIE[self::COOKIE_PREFIX . $this->sessionConfig->getSessionContext()] = $token;
199207
}
200208
}
201209

@@ -212,6 +220,11 @@ public function serializeSessionData($array)
212220
return $result;
213221
}
214222

223+
/**
224+
* @param $session_data
225+
* @return array
226+
* @throws JwtSessionException
227+
*/
215228
public function unSerializeSessionData($session_data)
216229
{
217230
$return_data = array();

0 commit comments

Comments
 (0)