I have an REST service on my webserver, written in php. I was wondering, what would be the best authentication (besides basic http access authentication). I\'ve heared of token-
You can use fire-base php JWT (JSON Web Token) for token based authentication.
1)Install php jwt by running composer command composer require firebase/php-jwt
require_once('vendor/autoload.php');
use \Firebase\JWT\JWT;
define('SECRET_KEY','Your-Secret-Key') // secret key can be a random string and keep in secret from anyone
define('ALGORITHM','HS512')
After that Generate your token
$tokenId = base64_encode(mcrypt_create_iv(32));
$issuedAt = time();
$notBefore = $issuedAt + 10; //Adding 10 seconds
$expire = $notBefore + 7200; // Adding 60 seconds
$serverName = 'http://localhost/php-json/'; /// set your domain name
/*
* Create the token as an array
*/
$data = [
'iat' => $issuedAt, // Issued at: time when the token was generated
'jti' => $tokenId, // Json Token Id: an unique identifier for the token
'iss' => $serverName, // Issuer
'nbf' => $notBefore, // Not before
'exp' => $expire, // Expire
'data' => [ // Data related to the logged user you can set your required data
'id' => "set your current logged user-id", // id from the users table
'name' => "logged user name", // name
]
];
$secretKey = base64_decode(SECRET_KEY);
/// Here we will transform this array into JWT:
$jwt = JWT::encode(
$data, //Data to be encoded in the JWT
$secretKey, // The signing key
ALGORITHM
);
$unencodedArray = ['jwt' => $jwt];
provide this token to your user "$jwt" . On each request user need to send token value with each request to validate user.
try {
$secretKey = base64_decode(SECRET_KEY);
$DecodedDataArray = JWT::decode($_REQUEST['tokVal'], $secretKey, array(ALGORITHM));
echo "{'status' : 'success' ,'data':".json_encode($DecodedDataArray)." }";die();
} catch (Exception $e) {
echo "{'status' : 'fail' ,'msg':'Unauthorized'}";die();
}
You can get step by step full configurations for php token based authentication