I have created this fake API just because I want to learn how to use JWT. It is a simple unsigned token exchange with two methods call: login and adminPassword.
I've used https://github.com/lcobucci/jwt as a JWT implementation.
This is the server code (index.php):
<?php
// https://github.com/lcobucci/jwt
require_once 'vendor/autoload.php';
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\ValidationData;
define('USERNAME', 'admin');
define('PASSWORD', 'p4ssw0rd');
function login($username, $password) {
if ($username == USERNAME && $password == PASSWORD) {
$token = (new Builder())->setIssuer('JWT Example')
->setAudience('JWT Example')
->setIssuedAt(time())
->setExpiration(time() + 3600)
->getToken();
return json_encode(['result' => 1, 'message' => 'Token generated successfully', 'token' => '' . $token,]);
} else {
return json_encode(['result' => 0, 'message' => 'Invalid username and/or password']);
}
}
function validateToken($token) {
try {
$token = (new Parser())->parse($token);
} catch (Exception $exception) {
return false;
}
$validationData = new ValidationData();
$validationData->setIssuer('JWT Example');
$validationData->setAudience('JWT Example');
return $token->validate($validationData);
}
function adminPassword($token) {
if (validateToken($token)) {
return json_encode(['result' => 1, 'message' => 'The admin\'s password is: ' . PASSWORD]);
} else {
return json_encode(['result' => 0, 'message' => 'Invalid token']);
}
}
$requestUri = trim($_SERVER['REQUEST_URI'], '/');
if ($requestUri == 'users/login') {
echo login($_POST['username'], $_POST['password']);
} else if ($requestUri == 'users/admin-password') {
echo adminPassword($_SERVER['HTTP_AUTHORIZATION']);
}
And the following is the client code:
<?php
// https://github.com/lcobucci/jwt
define('SERVER_URL', 'http://localhost:9999/');
function httpPost($url, $data = [], $headers = []) {
$options = [
'http' => [
'method' => 'POST',
'header' => array_merge(['Content-type: application/x-www-form-urlencoded'], $headers),
'content' => http_build_query($data),
],
];
$context = stream_context_create($options);
return file_get_contents($url, false, $context);
}
$url = SERVER_URL . 'users/login';
$response = httpPost($url, ['username' => 'admin', 'password' => 'p4ssw0rd']);
$response = json_decode($response);
$url = SERVER_URL . 'users/admin-password';
echo httpPost($url, [], ["Authorization: Bearer <{$response->token}>",]);
Dependencies (composer.json):
{
"name": "ns/jwtexampleapp",
"require": {
"lcobucci/jwt": "^3.1"
},
"authors": [
{
"name": "Author name",
"email": "[email protected]"
}
]
}
The next step is to learn about token signatures.
I know the code could be better. Actually I'm focused on the JWT concepts. Please analyse the code with that in mind ...
Am I following the right path? Is it a good representation about the JWT concepts?