georgechem/jwt-auth

Simple library to generate and validate json web token

v1.0.1 2021-10-25 14:03 UTC

This package is auto-updated.

Last update: 2024-09-07 18:13:15 UTC


README

Use composer to install:

composer require georgechem/jwt-auth

In root directory of your project create .env File like this

SERVER_SECRET='your server secret'
TOKEN_EXPIRE='5 minutes' // use time according to your needs
SERVER_DOMAIN = 'example.com' // server domain
HEADER_NAME='jwt-token' //name of header where jwt will be put
COOKIE_DOMAIN=localhost // for cookie verification
COOKIE_EXPIRE=60 cookie expire time in seconds

To generate token: in your entry point, generally index.php but can be any .php file

To obtain token do POST request to entry point with following data:

$_POST['email'] and $_POST['password'] // data used internally to generate JWT
require __DIR__ . '/vendor/autoload.php';
$jwt = Jwt::getInstance();
// echo json response which can be consumed in javascript
$jwt->generate()->jsonResponse();

To verify token and authenticate/authorize user in entry point:

$jwt = Jwt::getInstance();
/**
 * Token verified successfully|fail
 * array[optional] may contain additional options for verifications
 * like: user role, server name etc...
 * @Return bool
 */ 
$jwt->verify(array());

Exemplary usage:

Obtain token for new or already registered user:

use Georgechem\JwtAuth\Jwt\Jwt;

require __DIR__ . '/vendor/autoload.php';

// coming from traditional form or javascript
$_POST['email'] = 'user@email.com';
$_POST['password'] = 'user_password';

$jwt = Jwt::getInstance();
// json response may be consumed by javascript and token can be stored 
// in local storage
$jwt->generate()->jsonResponse();

Verify token for request

use Georgechem\JwtAuth\Jwt\Jwt;

require __DIR__ . '/vendor/autoload.php';

$jwt = Jwt::getInstance();
$_SERVER['jwt-token'] = 'that.token.should_be_from.header';
// if token is valid (not expired or malformed etc.)
if($jwt->verify()){
    //can use token data to do additional security checks manually
    var_dump($jwt->tokenData());
}