Skip to content

Instantly share code, notes, and snippets.

@kidino
Created December 1, 2018 03:02
Show Gist options
  • Save kidino/b9c46c4b27bfe8461631f4c58e8f5d3d to your computer and use it in GitHub Desktop.
Save kidino/b9c46c4b27bfe8461631f4c58e8f5d3d to your computer and use it in GitHub Desktop.
Login to WordPress web with JWT
<?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 Authentication for WP REST API
https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/
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-authentication-for-wp-rest-api/includes/vendor/autoload.php');
use \Firebase\JWT\JWT;
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('&amp;', '&', 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, $secret_key, array('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;
}
}
@kidino
Copy link
Author

kidino commented Jun 28, 2021 via email

@blainelawson
Copy link

blainelawson commented Jul 9, 2021 via email

@timlg07
Copy link

timlg07 commented Jun 18, 2023

It does not work anymore, see my updated fork of this gist.

(https://stackoverflow.com/a/72310650/6336728)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment