forked from usefulteam/jwt-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
class-auth.php
753 lines (654 loc) · 20.9 KB
/
class-auth.php
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
<?php
/**
* Setup JWT-Auth.
*
* @package jwt-auth
*/
namespace JWTAuth;
use Exception;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;
use Firebase\JWT\JWT;
/**
* The public-facing functionality of the plugin.
*/
class Auth {
/**
* The namespace to add to the api calls.
*
* @var string The namespace to add to the api call
*/
private $namespace;
/**
* Store errors to display if the JWT is wrong
*
* @var WP_REST_Response
*/
private $jwt_error = null;
/**
* Collection of translate-able messages.
*
* @var array
*/
private $messages = array();
/**
* The REST API slug.
*
* @var string
*/
private $rest_api_slug = 'wp-json';
/**
* Setup action & filter hooks.
*/
public function __construct() {
$this->namespace = 'jwt-auth/v1';
$this->messages = array(
'jwt_auth_no_auth_header' => __( 'Authorization header not found.', 'jwt-auth' ),
'jwt_auth_bad_auth_header' => __( 'Authorization header malformed.', 'jwt-auth' ),
);
}
/**
* Add the endpoints to the API
*/
public function register_rest_routes() {
register_rest_route(
$this->namespace,
'token',
array(
'methods' => 'POST',
'callback' => array( $this, 'get_token' ),
'permission_callback' => '__return_true',
)
);
register_rest_route(
$this->namespace,
'token/validate',
array(
'methods' => 'POST',
'callback' => array( $this, 'validate_token' ),
'permission_callback' => '__return_true',
)
);
register_rest_route(
$this->namespace,
'token/refresh',
array(
'methods' => 'POST',
'callback' => array( $this, 'refresh_token' ),
'permission_callback' => '__return_true',
)
);
}
/**
* Add CORs suppot to the request.
*/
public function add_cors_support() {
$enable_cors = defined( 'JWT_AUTH_CORS_ENABLE' ) ? JWT_AUTH_CORS_ENABLE : false;
if ( $enable_cors && !headers_sent() ) {
$headers = apply_filters( 'jwt_auth_cors_allow_headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization, Cookie' );
header( sprintf( 'Access-Control-Allow-Headers: %s', $headers ) );
}
}
/**
* Authenticate user either via wp_authenticate or custom auth (e.g: OTP).
*
* @param string $username The username.
* @param string $password The password.
* @param mixed $custom_auth The custom auth data (if any).
*
* @return WP_User|WP_Error $user Returns WP_User object if success, or WP_Error if failed.
*/
public function authenticate_user( $username, $password, $custom_auth = '' ) {
// If using custom authentication.
if ( $custom_auth ) {
$custom_auth_error = new WP_Error( 'jwt_auth_custom_auth_failed', __( 'Custom authentication failed.', 'jwt-auth' ) );
/**
* Do your own custom authentication and return the result through this filter.
* It should return either WP_User or WP_Error.
*/
$user = apply_filters( 'jwt_auth_do_custom_auth', $custom_auth_error, $username, $password, $custom_auth );
} else {
$user = wp_authenticate( $username, $password );
}
return $user;
}
/**
* Get token by sending POST request to jwt-auth/v1/token.
*
* @param WP_REST_Request $request The request.
* @return WP_REST_Response The response.
*/
public function get_token( WP_REST_Request $request ) {
$secret_key = defined( 'JWT_AUTH_SECRET_KEY' ) ? JWT_AUTH_SECRET_KEY : false;
$username = $request->get_param( 'username' );
$password = $request->get_param( 'password' );
$custom_auth = $request->get_param( 'custom_auth' );
// First thing, check the secret key if not exist return a error.
if ( ! $secret_key ) {
return new WP_REST_Response(
array(
'success' => false,
'statusCode' => 500,
'code' => 'jwt_auth_bad_config',
'message' => __( 'JWT is not configured properly.', 'jwt-auth' ),
'data' => array(),
),
500
);
}
if ( isset( $_COOKIE['refresh_token'] ) ) {
$device = $request->get_param( 'device' ) ?: '';
$user_id = $this->validate_refresh_token( $_COOKIE['refresh_token'], $device );
// If we receive a REST response, then validation failed.
if ( $user_id instanceof WP_REST_Response ) {
return $user_id;
}
$user = get_user_by( 'id', $user_id );
} else {
$user = $this->authenticate_user( $username, $password, $custom_auth );
}
// If the authentication is failed return error response.
if ( is_wp_error( $user ) ) {
$error_code = $user->get_error_code();
return new WP_REST_Response(
array(
'success' => false,
'statusCode' => 401,
'code' => $error_code,
'message' => strip_tags( $user->get_error_message( $error_code ) ),
'data' => array(),
),
401
);
}
// Valid credentials, the user exists, let's generate the token.
$response = $this->generate_token( $user, false );
// Add the refresh token as a HttpOnly cookie to the response.
if ( $username && $password ) {
$this->send_refresh_token( $user, $request );
}
return $response;
}
/**
* Generate access token.
*
* @param WP_User $user The WP_User object.
* @param bool $return_raw Whether or not to return as raw token string.
*
* @return WP_REST_Response|string Return as raw token string or as a formatted WP_REST_Response.
*/
public function generate_token( $user, $return_raw = true ) {
$secret_key = defined( 'JWT_AUTH_SECRET_KEY' ) ? JWT_AUTH_SECRET_KEY : false;
$issued_at = time();
$not_before = $issued_at;
$not_before = apply_filters( 'jwt_auth_not_before', $not_before, $issued_at );
$expire = $issued_at + ( MINUTE_IN_SECONDS * 10 );
$expire = apply_filters( 'jwt_auth_expire', $expire, $issued_at );
$payload = array(
'iss' => $this->get_iss(),
'iat' => $issued_at,
'nbf' => $not_before,
'exp' => $expire,
'data' => array(
'user' => array(
'id' => $user->ID,
),
),
);
$alg = $this->get_alg();
// Let the user modify the token data before the sign.
$token = JWT::encode( apply_filters( 'jwt_auth_payload', $payload, $user ), $secret_key, $alg );
// If return as raw token string.
if ( $return_raw ) {
return $token;
}
// The token is signed, now create object with basic info of the user.
$response = array(
'success' => true,
'statusCode' => 200,
'code' => 'jwt_auth_valid_credential',
'message' => __( 'Credential is valid', 'jwt-auth' ),
'data' => array(
'token' => $token,
'id' => $user->ID,
'email' => $user->user_email,
'nicename' => $user->user_nicename,
'firstName' => $user->first_name,
'lastName' => $user->last_name,
'displayName' => $user->display_name,
),
);
// Let the user modify the data before send it back.
return apply_filters( 'jwt_auth_valid_credential_response', $response, $user );
}
/**
* Sends a new refresh token.
*
* @param \WP_User $user The WP_User object.
* @param \WP_REST_Request $request The request.
*
* @return void
*/
public function send_refresh_token( \WP_User $user, \WP_REST_Request $request ) {
$refresh_token = bin2hex( random_bytes( 32 ) );
$created = time();
$expires = $created + DAY_IN_SECONDS * 30;
$expires = apply_filters( 'jwt_auth_refresh_expire', $expires, $created );
setcookie( 'refresh_token', $user->ID . '.' . $refresh_token, $expires, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true );
// Save new refresh token for the user, replacing the previous one.
// The refresh token is rotated for the passed device only, not affecting
// other devices.
$user_refresh_tokens = get_user_meta( $user->ID, 'jwt_auth_refresh_tokens', true );
if ( ! is_array( $user_refresh_tokens ) ) {
$user_refresh_tokens = array();
}
$device = $request->get_param( 'device' ) ?: '';
$user_refresh_tokens[ $device ] = array(
'token' => $refresh_token,
'expires' => $expires,
);
update_user_meta( $user->ID, 'jwt_auth_refresh_tokens', $user_refresh_tokens );
// Store next expiry for cron_purge_expired_refresh_tokens event.
$expires_next = $expires;
foreach ( $user_refresh_tokens as $device ) {
if ( $device['expires'] < $expires_next ) {
$expires_next = $device['expires'];
}
}
update_user_meta( $user->ID, 'jwt_auth_refresh_tokens_expires_next', $expires_next );
}
/**
* Get the token issuer.
*
* @return string The token issuer (iss).
*/
public function get_iss() {
return apply_filters( 'jwt_auth_iss', get_bloginfo( 'url' ) );
}
/**
* Get the supported jwt auth signing algorithm.
*
* @see https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
*
* @return string $alg
*/
public function get_alg() {
return apply_filters( 'jwt_auth_alg', 'HS256' );
}
/**
* Determine if given response is an error response.
*
* @param mixed $response The response.
* @return boolean
*/
public function is_error_response( $response ) {
if ( ! empty( $response ) && property_exists( $response, 'data' ) && is_array( $response->data ) ) {
if ( ! isset( $response->data['success'] ) || ! $response->data['success'] ) {
return true;
}
}
return false;
}
/**
* Public token validation function based on Authorization header.
*
* @param bool $return_response Either to return full WP_REST_Response or to return the payload only.
*
* @return WP_REST_Response | Array Returns WP_REST_Response or token's $payload.
*/
public function validate_token( $return_response = true ) {
/**
* Looking for the HTTP_AUTHORIZATION header, if not present just
* return the user.
*/
$headerkey = apply_filters( 'jwt_auth_authorization_header', 'HTTP_AUTHORIZATION' );
$auth = isset( $_SERVER[ $headerkey ] ) ? $_SERVER[ $headerkey ] : false;
// Double check for different auth header string (server dependent).
if ( ! $auth ) {
$auth = isset( $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ) ? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] : false;
}
if ( ! $auth ) {
return new WP_REST_Response(
array(
'success' => false,
'statusCode' => 401,
'code' => 'jwt_auth_no_auth_header',
'message' => $this->messages['jwt_auth_no_auth_header'],
'data' => array(),
),
401
);
}
/**
* The HTTP_AUTHORIZATION is present, verify the format.
* If the format is wrong return the user.
*/
list($token) = sscanf( $auth, 'Bearer %s' );
if ( ! $token ) {
return new WP_REST_Response(
array(
'success' => false,
'statusCode' => 401,
'code' => 'jwt_auth_bad_auth_header',
'message' => $this->messages['jwt_auth_bad_auth_header'],
'data' => array(),
),
401
);
}
// Get the Secret Key.
$secret_key = defined( 'JWT_AUTH_SECRET_KEY' ) ? JWT_AUTH_SECRET_KEY : false;
if ( ! $secret_key ) {
return new WP_REST_Response(
array(
'success' => false,
'statusCode' => 401,
'code' => 'jwt_auth_bad_config',
'message' => __( 'JWT is not configured properly.', 'jwt-auth' ),
'data' => array(),
),
401
);
}
// Try to decode the token.
try {
$alg = $this->get_alg();
$payload = JWT::decode( $token, $secret_key, array( $alg ) );
// The Token is decoded now validate the iss.
if ( $payload->iss !== $this->get_iss() ) {
// The iss do not match, return error.
return new WP_REST_Response(
array(
'success' => false,
'statusCode' => 401,
'code' => 'jwt_auth_bad_iss',
'message' => __( 'The iss do not match with this server.', 'jwt-auth' ),
'data' => array(),
),
401
);
}
// Check the user id existence in the token.
if ( ! isset( $payload->data->user->id ) ) {
// No user id in the token, abort!!
return new WP_REST_Response(
array(
'success' => false,
'statusCode' => 401,
'code' => 'jwt_auth_bad_request',
'message' => __( 'User ID not found in the token.', 'jwt-auth' ),
'data' => array(),
),
401
);
}
// So far so good, check if the given user id exists in db.
$user = get_user_by( 'id', $payload->data->user->id );
if ( ! $user ) {
// No user id in the token, abort!!
return new WP_REST_Response(
array(
'success' => false,
'statusCode' => 401,
'code' => 'jwt_auth_user_not_found',
'message' => __( "User doesn't exist", 'jwt-auth' ),
'data' => array(),
),
401
);
}
// Check extra condition if exists.
$failed_msg = apply_filters( 'jwt_auth_extra_token_check', '', $user, $token, $payload );
if ( ! empty( $failed_msg ) ) {
// No user id in the token, abort!!
return new WP_REST_Response(
array(
'success' => false,
'statusCode' => 401,
'code' => 'jwt_auth_obsolete_token',
'message' => __( 'Token is obsolete', 'jwt-auth' ),
'data' => array(),
),
401
);
}
// Everything looks good, return the payload if $return_response is set to false.
if ( ! $return_response ) {
return $payload;
}
$response = array(
'success' => true,
'statusCode' => 200,
'code' => 'jwt_auth_valid_token',
'message' => __( 'Token is valid', 'jwt-auth' ),
'data' => array(),
);
$response = apply_filters( 'jwt_auth_valid_token_response', $response, $user, $token, $payload );
// Otherwise, return success response.
return new WP_REST_Response( $response );
} catch ( Exception $e ) {
// Something is wrong when trying to decode the token, return error response.
return new WP_REST_Response(
array(
'success' => false,
'statusCode' => 401,
'code' => 'jwt_auth_invalid_token',
'message' => $e->getMessage(),
'data' => array(),
),
401
);
}
}
/**
* Validates refresh token and generates a new refresh token.
*
* @param WP_REST_Request $request The request.
* @return WP_REST_Response Returns WP_REST_Response.
*/
public function refresh_token( WP_REST_Request $request ) {
if ( ! isset( $_COOKIE['refresh_token'] ) ) {
return new WP_REST_Response(
array(
'success' => false,
'statusCode' => 401,
'code' => 'jwt_auth_no_auth_cookie',
'message' => __( 'Refresh token cookie not found.', 'jwt-auth' ),
),
401
);
}
$device = $request->get_param( 'device' ) ?: '';
$user_id = $this->validate_refresh_token( $_COOKIE['refresh_token'], $device );
if ( $user_id instanceof WP_REST_Response ) {
return $user_id;
}
// Generate a new access token.
$user = get_user_by( 'id', $user_id );
$this->send_refresh_token( $user, $request );
$response = array(
'success' => true,
'statusCode' => 200,
'code' => 'jwt_auth_valid_token',
'message' => __( 'Token is valid', 'jwt-auth' ),
);
return new WP_REST_Response( $response );
}
/**
* Validates refresh token.
*
* @param string $refresh_token_cookie The refresh token to validate.
* @param string $device The device of the refresh token.
* @return int|WP_REST_Response Returns user ID if valid or WP_REST_Response on error.
*/
public function validate_refresh_token( $refresh_token_cookie, $device ) {
$parts = explode( '.', $refresh_token_cookie );
if ( count( $parts ) !== 2 || empty( intval( $parts[0] ) ) || empty( $parts[1] ) ) {
return new WP_REST_Response(
array(
'success' => false,
'statusCode' => 401,
'code' => 'jwt_auth_invalid_refresh_token',
'message' => __( 'Invalid refresh token', 'jwt-auth' ),
),
401
);
}
// The refresh token must match the last issued refresh token for the passed
// device.
$user_id = intval( $parts[0] );
$user_refresh_tokens = get_user_meta( $user_id, 'jwt_auth_refresh_tokens', true );
$refresh_token = $parts[1];
if ( empty( $user_refresh_tokens[ $device ] ) ||
$user_refresh_tokens[ $device ]['token'] !== $refresh_token ||
$user_refresh_tokens[ $device ]['expires'] < time()
) {
return new WP_REST_Response(
array(
'success' => false,
'statusCode' => 401,
'code' => 'jwt_auth_obsolete_token',
'message' => __( 'Token is obsolete', 'jwt-auth' ),
),
401
);
}
return $user_id;
}
/**
* This is our Middleware to try to authenticate the user according to the token sent.
*
* @param int|bool $user_id User ID if one has been determined, false otherwise.
* @return int|bool User ID if one has been determined, false otherwise.
*/
public function determine_current_user( $user_id ) {
/**
* This hook only should run on the REST API requests to determine
* if the user in the Token (if any) is valid, for any other
* normal call ex. wp-admin/.* return the user.
*
* @since 1.2.3
*/
$this->rest_api_slug = get_option( 'permalink_structure' ) ? rest_get_url_prefix() : '?rest_route=/';
$valid_api_uri = strpos( $_SERVER['REQUEST_URI'], $this->rest_api_slug );
if ( ! $valid_api_uri ) {
return $user_id;
}
/**
* If the request URI is for validate the token don't do anything,
* This avoid double calls to the validate_token function.
*/
$validate_uri = strpos( $_SERVER['REQUEST_URI'], 'token/validate' );
if ( $validate_uri > 0 ) {
return $user_id;
}
$payload = $this->validate_token( false );
// If $payload is an error response, then return the default $user_id.
if ( $this->is_error_response( $payload ) ) {
if ( 'jwt_auth_no_auth_header' === $payload->data['code'] ||
'jwt_auth_bad_auth_header' === $payload->data['code']
) {
$request_uri = $_SERVER['REQUEST_URI'];
$rest_api_slug = home_url( '/' . $this->rest_api_slug, 'relative' );
if ( strpos( $request_uri, $rest_api_slug . '/jwt-auth/v1/token' ) !== 0 ) {
// Whitelist some endpoints by default (without trailing * char).
$default_whitelist = array(
// WooCommerce namespace.
$rest_api_slug . '/wc/',
$rest_api_slug . '/wc-admin/',
$rest_api_slug . '/wc-auth/',
$rest_api_slug . '/wc-analytics/',
// WordPress namespace.
$rest_api_slug . '/wp/v2/',
$rest_api_slug . '/oembed/',
);
// Well, we let you adjust this default whitelist :).
$default_whitelist = apply_filters( 'jwt_auth_default_whitelist', $default_whitelist );
$is_ignored = false;
foreach ( $default_whitelist as $endpoint ) {
if ( false !== stripos( $request_uri, $endpoint ) ) {
$is_ignored = true;
break;
}
}
if ( ! $is_ignored ) {
if ( ! $this->is_whitelisted() ) {
$this->jwt_error = $payload;
}
}
}
} else {
$this->jwt_error = $payload;
}
return $user_id;
}
// Everything is ok here, return the user ID stored in the token.
return $payload->data->user->id;
}
/**
* Check whether or not current endpoint is whitelisted.
*
* @return bool
*/
public function is_whitelisted() {
$whitelist = apply_filters( 'jwt_auth_whitelist', array() );
if ( empty( $whitelist ) || ! is_array( $whitelist ) ) {
return false;
}
$request_uri = $_SERVER['REQUEST_URI'];
$request_method = $_SERVER['REQUEST_METHOD'];
$prefix = get_option( 'permalink_structure' ) ? rest_get_url_prefix() : '?rest_route=/';
$split = explode( $prefix, $request_uri );
$request_uri = '/' . $prefix . ( ( count( $split ) > 1 ) ? $split[1] : $split[0] );
// Only use string before "?" sign if permalink is enabled.
if ( get_option( 'permalink_structure' ) && false !== stripos( $request_uri, '?' ) ) {
$split = explode( '?', $request_uri );
$request_uri = $split[0];
}
// Let's remove trailingslash for easier checking.
$request_uri = untrailingslashit( $request_uri );
foreach ( $whitelist as $endpoint ) {
if ( is_array( $endpoint ) ) {
$method = $endpoint['method'];
$path = $endpoint['path'];
} else {
$method = null;
$path = $endpoint;
}
// If the endpoint doesn't contain * sign.
if ( false === stripos( $path, '*' ) ) {
$path = untrailingslashit( $path );
if ( $path === $request_uri && ( ! isset( $method ) || $method === $request_method ) ) {
return true;
}
} else {
$regex = '/' . str_replace( '/', '\/', $path ) . '/';
if ( preg_match( $regex, $request_uri ) && ( ! isset( $method ) || $method === $request_method ) ) {
return true;
}
}
}
return false;
}
/**
* Filter to hook the rest_pre_dispatch, if there is an error in the request
* send it, if there is no error just continue with the current request.
*
* @param mixed $result Can be anything a normal endpoint can return, or null to not hijack the request.
* @param WP_REST_Server $server Server instance.
* @param WP_REST_Request $request The request.
*
* @return mixed $result
*/
public function rest_pre_dispatch( $result, WP_REST_Server $server, WP_REST_Request $request ) {
if ( $this->is_error_response( $this->jwt_error ) ) {
return $this->jwt_error;
}
if ( empty( $result ) ) {
return $result;
}
return $result;
}
}