-
Notifications
You must be signed in to change notification settings - Fork 1
/
jwt.module
263 lines (223 loc) · 6.88 KB
/
jwt.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
<?php
/**
* @file
* Module file for JWT module.
*/
/**
* Implements hook_permission().
*/
function jwt_permission() {
return array(
'administer_jwt' => array(
'title' => t('Administer JSON Web Tokens.')
),
);
}
/**
* Implements hook_menu().
* Provides admin page to configure JWT settings.
*/
function jwt_menu() {
$items = array();
$items['admin/config/administration/jwt'] = array(
'title' => 'Administer JWT Tokens',
'description' => 'Page to set up and administer site-wide JWT tokens',
'page callback' => 'backdrop_get_form',
'page arguments' => array('jwt_configuration_form'),
'access arguments' => array('administer_jwt'),
);
return $items;
}
/**
* Implements hook_form().
* JWT Admin Page.
*/
function jwt_configuration_form($form, &$form_state) {
$jwt_secret = state_get('jwt secret');
$timeout = state_get('jwt timeout');
$form['#attached']['js'][] = array(
'type' => 'file',
'data' => backdrop_get_path('module', 'jwt') . '/admin-scripts.js',
);
$form['jwt_secret'] = array(
'#type' => 'textfield',
'#size' => '32',
'#title' => 'Secret Key',
'#default_value' => $jwt_secret,
'#maxlength' => '1024',
);
$form['generate_secret'] = array(
'#type' => 'button',
'#value' => 'Generate Secret Key',
'#attributes' => array('onclick' => 'generateSecret();return false'),
);
$form['default_timeout'] = array(
'#type' => 'textfield',
'#size' => '32',
'#default_value' => $timeout,
'#title' => 'Default Timeout (in seconds)',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Save',
);
return $form;
}
/**
* Implements hook_form_submit().
* JWT admin page form submit handler.
*/
function jwt_configuration_form_submit($form, &$form_state) {
$timeout = $form_state['values']['default_timeout'];
state_set('jwt timeout', $timeout);
try{
$secret = $form_state['values']['jwt_secret'];
state_set('jwt secret', $secret);
backdrop_set_message(t('Successfully set JWT secret key.'), 'status');
} catch( exception $e ) {
backdrop_set_message(t('Could not set jwt secret: '.$e->getMessage()), 'error');
watchdog('jwt', $e, array(), WATCHDOG_ERROR);
}
}
/**
* Helper function to convert encoded JSON to web safe string.
*/
function _jwt_base64_url_encode($text) {
return str_replace(
['+', '/', '='],
['-', '_', ''],
base64_encode($text)
);
}
/**
* Public function that allows for the creation of JWTs.
*
* @param array $payload_data Associative array to encode as JWT payload.
* @param string|int $expiration (Optional) argument to specify timeout in seconds.
* @param string $secret (Optional) Specify secret to encode JWT with.
*
* @return string A signed JWT string.
*/
function encode_jwt($payload_data, $expiration=false, $secret=false) {
$current_time = time();
$expiration = $expiration ? (int) $expiration : (int) state_get('jwt timeout');
$payload_data['expiration'] = $current_time + $expiration;
// Create token header.
$header = json_encode([
'typ' => 'JWT',
'alg' => 'HS256',
]);
// Create token payload.
$payload = json_encode($payload_data);
// Encode Header.
$base64_url_header = _jwt_base64_url_encode($header);
// Encode Payload.
$base64_url_payload = _jwt_base64_url_encode($payload);
// Encode Signature.
$base64_url_signature = _jwt_encode_signature($base64_url_header, $base64_url_payload, $secret);
// Create JWT.
$jwt = $base64_url_header . '.' . $base64_url_payload . '.' . $base64_url_signature;
return $jwt;
}
/**
* Helper function to sign encoded JSON header and payload.
*/
function _jwt_encode_signature($base64_url_header, $base64_url_payload, $secret=false) {
if(!$secret) {
$secret = state_get('jwt secret');
}else {
}
// Create Signature.
$signature = hash_hmac('sha256', $base64_url_header . '.' . $base64_url_payload, $secret, true);
// Encode Signature.
return _jwt_base64_url_encode($signature);
}
/**
* Helper function to decode JWT without validation.
*/
function _jwt_decode($jwt) {
if (!$jwt) {
watchdog('JWT', 'JWT Verification Failed: No JWT token provided.', array(), WATCHDOG_ALERT);
return false;
}
$current_time = time();
$token_parts = explode('.', $jwt);
$length = count($token_parts);
if($length < 3 || $length > 3) {
watchdog('JWT', 'JWT Validation Failed: Invalid format.', array(), WATCHDOG_ALERT);
return false;
}
$decoded_jwt = array();
$decoded_jwt['header'] = base64_decode($token_parts[0]);
$decoded_jwt['base64_payload'] = base64_decode($token_parts[1]);
$decoded_jwt['signature'] = $token_parts[2];
$decoded_jwt['expiration'] = $decoded_jwt['payload']->expiration;
return $decoded_jwt;
}
/**
* Public function that verifies JWT authenticity.
*
* @param string $jwt JWT string.
* @param boolean $secret (Optional) Specify secret to verify token with.
*
* @return mixed
* Returns either false for invalid JWTs or Object with JWT payload as keys->values.
*/
function validate_jwt($jwt, $secret=false) {
$decoded_jwt = _jwt_decode($jwt);
// Check expiration time.
if ($decoded_jwt['expiration'] < $current_time) {
return false;
}
// Build Signature.
$base64_url_header = _jwt_base64_url_encode($decoded_jwt['header']);
$base64_url_payload = _jwt_base64_url_encode($decoded_jwt['base64_payload']);
$base64_url_signature = _jwt_encode_signature($base64_url_header, $base64_url_payload, $secret);
// Verify Signature.
$valid_signature = ( $base64_url_signature === $decoded_jwt['signature'] );
if (!$valid_signature) {
return false;
} else {
return json_decode($decoded_jwt['base64_payload']);
}
}
/**
* Public function that decodes authentic JWTs.
*
* @param string $jwt JWT string.
* @param boolean $validate (Optional) Default value (false) validates jwt.
* @param string $secret (Optional) Specify valid secret key.
*
* @return mixed
* Returns either false for invalid JWTs or Object with JWT payload as keys->values.
*/
function decode_jwt($jwt, $validate=true, $secret=false) {
if($validate){
return validate_jwt($jwt, $secret);
} else {
return _jwt_decode($jwt);
}
}
/**
* Public function to decode JWT header.
*
* @param string $jwt JWT string.
*
* @param bool $validate (Optional) Verify authenticity of header.
*
* @return Object
* Returns Object with key->value pairs.
*/
function decode_jwt_header($jwt, $validate=false, $secret=false) {
if($validate && !validate_jwt($jwt, $secret)) {
return false;
}
$token_parts = explode('.', $jwt);
$length = count($token_parts);
if($length < 3 || $length > 3) {
watchdog('JWT', 'JWT Validation Failed: Invalid format.', array(), WATCHDOG_ALERT);
return false;
}
$header = base64_decode($token_parts[0]);
return json_decode($header);
}