-
-
Save timlg07/c2e3c6f34952e8abc1f5eb8115acdc68 to your computer and use it in GitHub Desktop.
Login to WordPress web with JWT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
JWT TOKEN LOGIN -- Automatically logs a user in a WordPress site with JWT | |
This script allows you to log a user into a WordPress site automatically | |
based on his/her JSON Web Token (JWT). This assumes that you use the | |
following plugin and set it up properly on your WordPress site to enable | |
JWT authentication via REST API. | |
JWT Auth – WordPress JSON Web Token Authentication | |
https://wordpress.org/plugins/jwt-auth | |
This file is to be placed along side your WordPress' index.php | |
Example use case : | |
You have an external system that uses the WordPress user database for login. | |
Login is done on that external system via WordPress REST API and using the | |
above mentioned plugin, where you will get a token. If you want to send the | |
user to the main WordPress site and have him/her automatically logged in, | |
you can send him/her to token-login.php?jwt=<token>, where <token> is the | |
token string from previous REST API authentication. | |
*/ | |
require('wp-blog-header.php'); | |
require('wp-content/plugins/jwt-auth/vendor/autoload.php'); | |
use \Firebase\JWT\JWT; | |
use \Firebase\JWT\Key; | |
if (!isset($_GET['jwt'])) { | |
header('Location: /wp-login.php'); | |
} | |
$token = $_GET['jwt']; | |
$token = decode_token($token); | |
if ($token !== false) { | |
$user_id = $token->data->user->id; | |
$user = get_userdata($user_id); | |
$user_login = $user->user_login; | |
wp_set_current_user($user_id); | |
wp_set_auth_cookie($user_id); | |
do_action('wp_login', $user_login); | |
// redirects to home | |
header('Location: '.home_url()); | |
} else { | |
$logout = str_replace('&', '&', wp_logout_url(home_url())); | |
header('Location: '.$logout); | |
} | |
function decode_token($token) { | |
$secret_key = defined('JWT_AUTH_SECRET_KEY') ? JWT_AUTH_SECRET_KEY : false; | |
if (!$secret_key) { | |
return false; | |
} | |
/** Try to decode the token */ | |
try { | |
$token = JWT::decode($token, new Key($secret_key, 'HS256')); | |
/** The Token is decoded now validate the iss */ | |
if ($token->iss != get_bloginfo('url')) { | |
return false; | |
} | |
/** So far so good, validate the user id in the token */ | |
if (!isset($token->data->user->id)) { | |
return false; | |
} | |
/** Everything looks good return the decoded token if the $output is false */ | |
return $token; | |
} catch (Exception $e) { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment