Ecommerce Shopify WordPress Discussion

JWT headless wordpress with javascript (custom plugin)

how to implement securly jwt with (vanilla or jquery) javascript and headless wordpress (php) not by using any plugin i have 2 servers* server 1 (vanilla js + html) app.example.com server 2 (wordpress php) example.com in front end i make this ajax call (js) let email = 'test@test.com'; let password = '123test'; $.ajax({ url: `https://example.com/wp-json/custom-route/v2/tologin/?email=${email}&password=${password}`, method: 'GET', credentials: 'include', success: function(data) { console.log(data) }, error: function(error) { console.log('error') } }); } in back end the rest endpoint of this request (cutom plugin for wordpress php) add_action('rest_api_init', function () { register_rest_route('custom-route/v2', '/tologin/', array( 'methods' => 'POST', 'callback' => 'generate_jwt', )); }); function generate_jwt(WP_REST_Request $request) { // get the username and password from the request $username = $request->get_param('username'); $password = $request->get_param('password'); // Authenticate the user $user = wp_authenticate($username, $password); // Check if the user is valid if (!is_wp_error($user)) { // Generate the JWT $issued_at = time(); $expiration_time = $issued_at + 1800; // 30 minutes expiration $token_data = array( 'iat' => $issued_at, 'exp' => $expiration_time, 'data' => array( 'username' => $username, 'user_id' => $user->ID, ), ); $token = jwt_encode($token_data); setcookie('token-name-of-cookie', $token, [ 'expires' => $expiration_time, 'path' => '/', 'domain' => '.example.com', 'secure' => true, 'httponly' => true, 'samesite' => 'Strict', ]); return rest_ensure_response(array('token' => $token)); } else { return rest_ensure_response(array('error' => 'Invalid credentials'), 401); } } function jwt_encode($data) { $secret_key = 'xxxxxxxxxxxxxxxx'; $header = json_encode(['alg' => 'HS256', 'typ' => 'JWT']); $payload = json_encode($data); $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header)); $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload)); $signature = hash_hmac('sha256', $base64UrlHeader . '.' . $base64UrlPayload, $secret_key, true); $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature)); return $base64UrlHeader . '.' . $base64UrlPayload . '.' . $base64UrlSignature; } SO FAR ITS OK i create the JWT Now for the cookie part on inpector > application > cookies i can't see it, but on inspector > network > cookies i see it. [token-name-of-cookie with the jwt...] after that i want make a new one request to a new rest end point to resive some data of the logedin user so on a button click i make this request from (js) function member_data() { $.ajax({ url: 'https://example.com/wp-json/custom-route/v2/getdata', method: 'GET', credentials: 'include', success: function(userdata) { console.log(userdata) }, error: function(error) { console.log('error') } }); } end the rest endpoint of this request (cutom plugin for wordpress php) <?php if ( ! defined( 'ABSPATH' ) ) {exit;} add_action('rest_api_init', function () { register_rest_route('custom-route/v2', '/getdata', array( 'methods' => 'GET', 'callback' => 'get_member_data', )); }); function get_member_data($request) { $token = isset($_COOKIE['token-name-of-cookie']) ? $_COOKIE['token-name-of-cookie'] : null; error_log("----- token --"); error_log($token); error_log("----- token --"); $decoded_token = jwt_decode($token); if ($decoded_token) { $user_id = $decoded_token->data->user_id; $user_data = array( 'user_id' => $user_id, ); return rest_ensure_response($user_data); } else { return rest_ensure_response(array('error' => 'Invalid token'), 401); } } function jwt_decode($token) { $secret_key = 'xxxxxxxxxxxxxxxx'; list($header, $payload, $signature) = explode('.', $token); $decoded_header = json_decode(base64_decode(str_replace(['-', '_'], ['+', '/'], $header)), true); $decoded_payload = json_decode(base64_decode(str_replace(['-', '_'], ['+', '/'], $payload)), true); $computed_signature = hash_hmac('sha256', $header . '.' . $payload, $secret_key, true); $computed_signature_base64 = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($computed_signature)); if ($signature === $computed_signature_base64) { return $decoded_payload; } else { return null; } } end there is the problem the $token is empty so i read "for security use httponly" "The browser automatically includes the HttpOnly cookie in the headers of subsequent requests to the same domain." In front end i can't create a httponly cookie (js has not access to httponly cookies) In back end i create it but i can't use it for new requests? *I could save it to a non httponly cookie in js or in local/session storage and send it i know.. but the right way is to be secure for xxs .... So can anybody help me and the rest of us that we have not implemented this yet? Thank you
TurboCommerce make the better internet purchasing globaly

Turbo Multi-language Translator

Make the better internet purchasing globaly

Turbosify SEO Speed Booster

5.0 (7) Free plan available
Get better conversions by improving store loading speed Installed

Turbo Multi-language Chat - AI Customer service in one hand

TurboCommerce make the better internet purchasing globaly
Our products

The help you need, when you need it

App by Turbo Engine

3 apps • 5.0 average rating

Turbosify Speed Booster

5.0 (7)
Get better conversions by optimizing shopify store Google page speed Installed

Turbosify Translator for Wordpress Woocommerce

5.0 (74) Free Wordpress Woocommerce Plugin
Translate your wordpress website to multiple language within 1 click, no configuration needed, no No technical required

Grow your business here

Whether you want to sell products down the street or around the world, we have all the tools you need.