<?php // set up the database connection $dsn = 'mysql:host=localhost;dbname=mydatabase'; $user = 'dbuser'; $password = 'dbpass'; $pdo = new PDO($dsn, $user, $password); // check for a valid JWT in the Authorization header $authHeader = $_SERVER['HTTP_AUTHORIZATION']; if (empty($authHeader)) { // no authorization header was provided http_response_code(401); echo 'Missing authorization header'; exit(); } // extract the JWT from the authorization header $jwt = sscanf($authHeader, 'Bearer %s')[0]; if (empty($jwt)) { // no JWT was provided http_response_code(401); echo 'Missing JWT'; exit(); } // decode the JWT to get the user's ID try { $decoded = JWT::decode($jwt, 'mysecretkey', ['HS256']); $userId = $decoded->userId; } catch (Exception $e) { // the JWT was invalid http_response_code(401); echo 'Invalid JWT'; exit(); } // get the users from the database $stmt = $pdo->prepare('SELECT * FROM users WHERE id = :userId'); $stmt->bindValue(':userId', $userId, PDO::PARAM_INT); $stmt->execute(); $users = $stmt->fetchAll(PDO::FETCH_ASSOC); // return the users as JSON header('Content-Type: application/json'); echo json_encode($users);
Now hoe to consume it :
async function getUsers() { // authenticate and get a JWT const response = await fetch('/login', { method: 'POST', body: JSON.stringify({username: 'myusername', password: 'mypassword'}), headers: { 'Content-Type': 'application/json' } }); const {jwt} = await response.json(); // use the JWT to get the users from the API const response = await fetch('/users', { headers: { 'Authorization': `Bearer ${jwt}` } }); const users = await response.json(); // do something with the users console.log(users); } getUsers();