I am trying to authenticate with Jwt. I found many examples about Jwt, but there is a place I don't understand. I can easily generate tokens using the library, but I cannot verify here is the library i use
composer require firebase/php-jwt
I'm creating a token
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
require_once('vendor/autoload.php');
use \Firebase\JWT\JWT;
define('SECRET_KEY','Super-Secret-Key');
define('ALGORITHM','HS256');
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$action = $_GET['action'];
login.php
if ($action == 'login') {
$email = 'freaky@jolly.com';
$password = '12345678';
if($email == "freaky@jolly.com" && $password == "12345678"){
$iat = time(); // time of token issued at
$nbf = $iat + 10; //not before in seconds
$exp = $iat + 60; // expire time of token in seconds
$token = array(
"iss" => "http://example.org",
"aud" => "http://example.com",
"iat" => $iat,
"nbf" => $nbf,
"exp" => $exp,
"data" => array(
"id" => 11,
"email" => $email
)
);
http_response_code(200);
$jwt = JWT::encode($token, SECRET_KEY);
$data_insert=array(
'access_token' => $jwt,
'id' => '007',
'name' => 'Jolly',
'time' => time(),
'username' => 'FreakyJolly',
'email' => 'contact@freakyjolly.com',
'status' => "success",
'message' => "Successfully Logged In"
);
}else{
$data_insert=array(
"data" => "0",
"status" => "invalid",
"message" => "Invalid Request"
);
}
} else if($action == 'stuff'){
if (! isset($_SERVER['argv'][1])) {
exit('Please provide a key to verify');
}
$jwt = $_SERVER['argv'][1];
try {
$decoded = JWT::decode($jwt, SECRET_KEY, array(ALGORITHM));
print_r($decoded);
}catch (Exception $e){
http_response_code(401);
$data_insert=array(
//"data" => $data_from_server,
"jwt" => $jwt,
"status" => "error",
"message" => $e->getMessage()
);
}
}
echo json_encode($data_insert);
Create Token: http://www.ismailcakir.com/jwt/test2.php?action=login
{"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9leGFtcGxlLm9yZyIsImF1ZCI6Imh0dHA6XC9cL2V4YW1wbGUuY29tIiwiaWF0IjoxNTg2NDM4NTg4LCJuYmYiOjE1ODY0Mzg1OTgsImV4cCI6MTU4NjQzODY0OCwiZGF0YSI6eyJpZCI6MTEsImVtYWlsIjoiZnJlYWt5QGpvbGx5LmNvbSJ9fQ.NylRpDkb4cLMxMGAg9ovmLerNf0dLPBHegqmPRDRxlE","id":"007","name":"Jolly","time":1586438588,"username":"FreakyJolly","email":"contact@freakyjolly.com","status":"success","message":"Successfully Logged In"}
Stuff: http://www.ismailcakir.com/jwt/test2.php?action=stuff
Here I get the warning that the argv variable is undefined and I can't call the token you created. After creating the token, I need to be able to call it without using a cookie or session. I tried many methods but I could not understand how to take.
As per documentation :
Note: This variable is not available when register_argc_argv is disabled.
Which most likely is your case. You can enable this in the config or alternatively use $_SERVER
superglobal which I recommend as this is immune to config differences and always works (incl. CLI):
$jwt = $_SERVER['argv'][1];
Same for $argc
.
Use the following instruction to check what you get as arguments:
<?php
var_dump($argv);
?>
From the official documentation, this is available as well as: $_SERVER['argv']
.
Please also note that $argv
and $argc
need to be declared global, while trying to access within a class method.
To be able to get the token with:
$ _SERVER ['argv'] [1]
Then, you need to run the script from the command line (CLI), ie: php <script_name> argc1 arg2...
, then you will be able to the parameters values from there, if you use a browser, or an API call, you need to use an HTTP method (GET/POST),
Or with a JSON receiving call:
file_get_contents("php://input");
It seems that you put everything in your code, your code needs to be reformulated.
If you generate the token in a file script, and you need to send it back to a different page, you need to use a GET/POST request, if the user provides a value and you need to save it or use it, you need to receive it with a method, below an example about how your code can work properly (many ways could be provided):
if ($action == 'login') {
$email = 'freaky@jolly.com';
$password = '12345678';
if($email == "freaky@jolly.com" && $password == "12345678"){
$iat = time(); // time of token issued at
$nbf = $iat + 10; //not before in seconds
$exp = $iat + 60; // expire time of token in seconds
$token = array(
"iss" => "http://example.org",
"aud" => "http://example.com",
"iat" => $iat,
"nbf" => $nbf,
"exp" => $exp,
"data" => array(
"id" => 11,
"email" => $email
)
);
http_response_code(200);
$jwt = JWT::encode($token, SECRET_KEY);
$_SESSION['token'] = $jwt;
// $_COOKIE['token'] = $jwt ;
// GET and POST can be used via a web form or CURL
$data_insert=array(
'access_token' => $jwt,
'id' => '007',
'name' => 'Jolly',
'time' => time(),
'username' => 'FreakyJolly',
'email' => 'contact@freakyjolly.com',
'status' => "success",
'message' => "Successfully Logged In"
);
}else{
$data_insert=array(
"data" => "0",
"status" => "invalid",
"message" => "Invalid Request"
);
}
} else if($action == 'stuff'){
/*
* How to receive the generated token
*/
if (!isset($_SESSION['token']))
// or (!isset($_POST['token']));
// or (!isset($_GET['token']));
// or (!isset($_COOKIE['token']));
{
exit('Please provide a key to verify');
}
$jwt = $_SESSION['token'];
// or $jwt = $_GET['token'];
// or $jwt = $_POST['token'];
// or $jwt = $_COOKIE['token'];
try {
$decoded = JWT::decode($jwt, SECRET_KEY, array(ALGORITHM));
print_r($decoded);
}catch (Exception $e){
http_response_code(401);
$data_insert=array(
//"data" => $data_from_server,
"jwt" => $jwt,
"status" => "error",
"message" => $e->getMessage()
);
}
}
echo json_encode($data_insert);
You can take a look on:
REST API Authentication Example in PHP – JWT Tutorial
https://www.codeofaninja.com/2018/09/rest-api-authentication-example-php-jwt-tutorial.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.