**Retrieve user token **
In my case, I want to recover the WordPress Authentication Token from my logged in user.
To recover this token, I use the plugin jwt-authentication-for-wp-api
Lien plugin : https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/
Here are the two endpoints proposed by the plugin that interest us:
This endpoint allows us to retrieve the token, using username' and password’
https://instance.fr/wp-json/jwt-auth/v1/token?username=username&password=password
This endpoint allows us to validate the token that we have just recovered
https://instance.fr/wp-json/jwt-auth/v1/token/validate?token
I already have a Javascript script that allows me to retrieve the token with my account credentials, and then use the latter to have the token validation message, which I put in the files of my wordpress theme. Here is the file path of the active theme on my WordPress instance:
instance.fr/httpdocs/wp-content/themes/astra-child/js/script.js
For now, I do everything in a test instance.
First, I retrieve the variables of the connected user from the filefunctions.php of the active theme.
instance.fr/httpdocs/wp-content/themes/astra-child/functions.php
functions.php
function transformation_variables_wp()
{
$current_user = wp_get_current_user();
wp_enqueue_script('transformation_variables_wp', get_stylesheet_directory_uri() . '/js/script.js');
wp_localize_script('transformation_variables_wp', 'my_script_var_wp', array(
'prenom_wp' => $current_user->user_firstname,
'nom_wp' => $current_user->user_lastname,
'courriel_wp' => $current_user->user_email,
'username_wp' => $current_user->user_login,
));
}
add_action('wp_enqueue_scripts', 'transformation_variables_wp');
I then transform these variables into Javascript, so that I can manipulate them in my script below.
script.js
// ---------------- User variables retrieved in WordPress --------------------
var prenom_e = my_script_var_wp.prenom_wp;
var nom_e = my_script_var_wp.nom_wp;
var courriel_e = my_script_var_wp.courriel_wp;
var username_e = my_script_var_wp.username_wp; //
// --- Transformation de variables --- //
const firstname = prenom_e;
const lastname = nom_e;
const email = courriel_e;
const username = username_e; //
const password = "password"; //
// --------------Variables------------------------------
const urlInfoClient = "https://www.instance.fr";
// -----------------------------------------------------
// ---------------- API Environment URL's --------------------
const urlGetToken = "https://instance.fr/wp-json/jwt-auth/v1/token";
const urlValidateToken = "https://instance.fr/wp-json/jwt-auth/v1/token/validate";
// -----------------------------------------------------
async function GenerateToken() {
console.log(" ");
console.log("GenerateToken() function");
const res = await fetch(
urlGetToken + `?username=${username}`+`&password=${password}`,
{
method: 'POST',
headers: {
"Content-type": "application/json; charset=UTF-8"
}
}
);
if (res.status !== 200) {
throw new Error(`Impossible de récuperer le token`);
}
let data = await res.json();
console.log(data);
if (data && data.token) {
letoken = data.token
} else {
console.log("La propriété 'token' n'existe pas dans la réponse JSON.");
}
}
async function UseToken() {
console.log(" ");
console.log("UseToken() function");
var token = letoken;
const res1 = await fetch(
urlValidateToken + `?${token}`,
{
method: 'POST',
headers: {
"Content-type": "application/json; charset=UTF-8",
"Authorization": `Bearer ${token}`
}
}
);
if (res1.status !== 200) { //
throw new Error(`Impossible de récuperer le token`);
}
let data1 = await res1.json();
console.log(data1);
return data1;
}
// ---------------------actions------------------
window.addEventListener('DOMContentLoaded', (event) => {
document.getElementById("auth_button").onclick = function () {
GenerateToken()
.then(() => UseToken())
.catch((erreur) => {
console.error(erreur);
});
}});
When I click the button, the console generates these results:
GenerateToken() function
{token: ‘token_generated’, user_email: ‘[email protected]’, user_nicename: ‘stackov’, user_display_name: ‘Stack Overflow’}
UseToken() function
code: “jwt_auth_valid_token”
data:{status: 200}
I put the password in the Javascript script variables, to make the token generation function work.
But I want to recover the login token, without having to enter the password in my request. My goal is to retrieve the token variable from the JSON reponse, and use it to connect to another instance, which is not a WordPress instance. This token will bridge between my WordPress instance and the other instance. For now I have not found secure ways to do so.
Thank you all.
I remain available for more information

