Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active December 13, 2023 03:08
Show Gist options
  • Save code-boxx/01485e124300c53b38686a5f482b5bfc to your computer and use it in GitHub Desktop.
Save code-boxx/01485e124300c53b38686a5f482b5bfc to your computer and use it in GitHub Desktop.
PHP MYSQL JWT Login

PHP MYSQL JWT LOGIN

https://code-boxx.com/jwt-login-authentication-php-mysql/

NOTES

  1. A copy of PHP-JWT is required but not included - Download and install Composer if you have not done so. Open the command line and navigate to your project folder – cd YOUR-HTTP-FOLDER, then run composer require firebase/php-jwt.
  2. Create a database and import 1-users.sql.
  3. Change the database and JWT settings in 2-lib-users.php to your own.
  4. Access 3-login.php in the browser, user is jon@doe.com and password is 123456.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

CREATE TABLE `users` (
`id` bigint(20) NOT NULL,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `email` (`email`),
ADD KEY `name` (`name`);
ALTER TABLE `users`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT;
INSERT INTO `users` (`id`, `name`, `email`, `password`) VALUES
(1, 'Jon Doe', 'jon@doe.com', '$2y$10$5S0BORM0dC/pVrddltxbg.Fa5EBa5zZDXxNhL5Jt57bCi1aFZpcee');
<?php
class User {
// (A) CONNECT TO DATABASE
public $error = "";
private $pdo = null;
private $stmt = null;
function __construct () {
$this->pdo = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET,
DB_USER, DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
}
// (B) CLOSE CONNECTION
function __destruct () {
if ($this->stmt!==null) { $this->stmt = null; }
if ($this->pdo!==null) { $this->pdo = null; }
}
// (C) RUN SQL QUERY
function query ($sql, $data=null) : void {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
}
// (D) SAVE USER
function save ($name, $email, $password, $id=null) {
$data = [$name, $email, password_hash($password, PASSWORD_DEFAULT)];
if ($id===null) {
$sql = "INSERT INTO `users` (`name`, `email`, `password`) VALUES (?,?,?)";
} else {
$sql = "UPDATE `users` SET `name`=?, `email`=?, `password`=? WHERE `id`=?";
$data[] = [$id];
}
$this->query($sql, $data);
return true;
}
// (E) GET USER
function get ($id) {
$this->query(
sprintf("SELECT * FROM `users` WHERE `%s`=?", is_numeric($id) ? "id" : "email" ),
[$id]
);
return $this->stmt->fetch();
}
// (F) VERIFY USER LOGIN
// RETURNS FALSE IF INVALID EMAIL/PASSWORD
// RETURNS JWT IF VALID
function login ($email, $password) {
// (F1) GET USER
$user = $this->get($email);
$valid = is_array($user);
// (F2) CHECK PASSWORD
if ($valid) { $valid = password_verify($password, $user["password"]); }
// (F3) RETURN JWT IF OK, FALSE IF NOT
if ($valid) {
require "vendor/autoload.php";
$now = strtotime("now");
return Firebase\JWT\JWT::encode([
"iat" => $now, // issued at - time when token is generated
"nbf" => $now, // not before - when this token is considered valid
"exp" => $now + 3600, // expiry - 1 hr (3600 secs) from now in this example
"jti" => base64_encode(random_bytes(16)), // json token id
"iss" => JWT_ISSUER, // issuer
"aud" => JWT_AUD, // audience
"data" => ["id" => $user["id"]] // whatever data you want to add
], JWT_SECRET, JWT_ALGO);
} else {
$this->error = "Invalid user/password";
return false;
}
}
// (G) VALIDATE JWT
// RETURN USER IF VALID
// RETURN FALSE IF INVALID
function validate ($jwt) {
// (G1) "UNPACK" ENCODED JWT
require "vendor/autoload.php";
try {
$jwt = Firebase\JWT\JWT::decode($jwt, new Firebase\JWT\Key(JWT_SECRET, JWT_ALGO));
$valid = is_object($jwt);
} catch (Exception $e) {
$this->error = $e->getMessage();
return false;
}
// (G2) GET USER
if ($valid) {
$user = $this->get($jwt->data->id);
$valid = is_array($user);
}
// (G3) RETURN RESULT
if ($valid) {
unset($user["password"]);
return $user;
} else {
$this->error = "Invalid JWT";
return false;
}
}
}
// (H) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
// (I) JWT STUFF - CHANGE TO YOUR OWN!
define("JWT_SECRET", "SECRET-KEY");
define("JWT_ISSUER", "YOUR-NAME");
define("JWT_AUD", "site.com");
define("JWT_ALGO", "HS512");
// (J) NEW USER OBJECT
$_USER = new User();
<?php
// (A) PROCESS LOGIN
// (A1) ALREADY SIGNED IN
if (isset($_COOKIE["jwt"])) {
require "2-lib-users.php";
$user = $_USER->validate($_COOKIE["jwt"]);
if ($user===false) { setcookie("jwt", null, -1); }
else { header("Location: 4b-admin.php"); exit(); }
}
// (A2) PROCESS SIGN IN
if (isset($_POST["email"]) && isset($_POST["password"])) {
require "2-lib-users.php";
$jwt = $_USER->login($_POST["email"], $_POST["password"]);
if ($jwt!==false) {
setcookie("jwt", $jwt);
header("Location: 4b-admin.php");
exit();
}
} ?>
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<meta charset="utf-8">
<link rel="stylesheet" href="x-dummy.css">
</head>
<body>
<!-- (B) MESSAGE -->
<?php if (isset($jwt)) { ?>
<div class="note"><?=$_USER->error?></div>
<?php } ?>
<!-- (C) LOGIN FORM -->
<form method="post">
<h1>LOGIN</h1>
<input type="email" placeholder="Email" name="email" required value="jon@doe.com">
<input type="password" placeholder="Password" name="password" required value="123456">
<input type="submit" value="Sign In">
</form>
</body>
</html>
<?php
// (A) JWT COOKIE NOT SET!
if (!isset($_COOKIE["jwt"])) { header("Location: 3-login.php"); exit(); }
// (B) VERIFY JWT
require "2-lib-users.php";
$user = $_USER->validate($_COOKIE["jwt"]);
if ($user===false || isset($_POST["logout"])) {
setcookie("jwt", null, -1);
header("Location: 3-login.php");
exit();
}
<?php
// (A) ACCESS CHECK
require "4a-protect.php";
// (B) SHOW THE PAGE ?>
<!DOCTYPE html>
<html>
<head>
<title>Dummy Admin Page</title>
<meta charset="utf-8">
<link rel="stylesheet" href="x-dummy.css">
</head>
<body>
<form method="post">
<h1>IT WORKS!</h1>
<?php print_r($user); ?>
<input type="hidden" name="logout" value="1">
<input type="submit" value="Logout">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<meta charset="utf-8">
<link rel="stylesheet" href="x-dummy.css">
<script src="5b-login-page.js"></script>
</head>
<body>
<form method="post" id="login" onsubmit="return login()">
<h1>LOGIN</h1>
<input type="email" placeholder="Email" name="email" required value="jon@doe.com">
<input type="password" placeholder="Password" name="password" required value="123456">
<input type="submit" value="Sign In">
</form>
</body>
</html>
function login () {
// (A) FORM DATA
let data = new FormData(document.getElementById("login"));
// (B) AJAX FETCH
fetch("5c-login-ajax.php", { method:"post", body:data })
.then(res => res.json())
.then(res => {
if (res.status) {
// (B1) STORE THE TOKEN IN LOCALSTORAGE
localStorage.setItem("jwt", res.msg);
/* (B2) IN INDEXED DATABSE
IDB.transaction("Settings", "readwrite")
.objectStore("Settings")
.add({"jwt":res.msg}); */
/* (B3) OR EVEN IN STORAGE CACHE
var jwtBlob = new Blob([res.msg], {type: "text/plain"});
var urlBlob = URL.createObjectURL(jwtBlob);
fetch(urlBlob)
.then(res => {
caches.open("NAME").then(cache => cache.put("jwt.txt", res));
URL.revokeObjectURL(urlBlob);
}); */
// (B4) DONE
location.href = "5d-api.html";
} else { alert(res.msg); }
})
.catch(err => console.error(err));
return false;
}
<?php
if (isset($_POST["email"]) && isset($_POST["password"])) {
// (A) LOAD LIBRARY
require "2-lib-users.php";
// (B) VERIFY CREDENTIALS
$jwt = $_USER->login($_POST["email"], $_POST["password"]);
echo json_encode([
"status" => $jwt===false ? false : true,
"msg" => $jwt === false ? $_USER->error : $jwt
]);
} else {
echo json_encode([
"status" => false,
"msg" => "Invalid email/password"
]);
}
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<meta charset="utf-8">
</head>
<body>
<script>
// (A) FORM DATA - JWT
let data = new FormData();
data.append("jwt", localStorage.getItem("jwt"));
data.append("key", "value");
// (B) ATTACH JWT IN FETCH CALL
fetch("5e-api.php", { method:"POST", body:data })
.then(res => res.text())
.then(txt => console.log(txt))
.catch(err => console.error(err));
</script>
</body>
</html>
<?php
// (A) JWT NOT SET!
if (!isset($_POST["jwt"])) { exit("NO"); }
// (B) VERIFY JWT
require "2-lib-users.php";
$user = $_USER->validate($_POST["jwt"]);
if ($user===false) { exit("NO"); }
// (C) PROCEED AS USUAL
echo "YES";
/* NOT IMPORTANT - CSS COSMETICS */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
body {
width: 500px;
padding: 15px;
margin: 0 auto;
}
div.note {
padding: 10px;
margin-bottom: 15px;
background: #ffecec;
}
form {
padding: 20px;
border: 1px solid #eee;
background: #f7f7f7;
}
form h1 { margin: 0 0 20px 0; }
input {
display: block;
width: 100%;
padding: 10px;
}
input[type=email], input[type=password] {
margin-bottom: 10px;
border: 1px solid #cdcdcd;
}
input[type=submit] {
margin-top: 20px;
border: 0;
color: #fff;
background: #ac1616;
cursor: pointer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment