[英]I can't verify user with jwt
I am trying to authenticate with Jwt.我正在尝试使用 Jwt 进行身份验证。 I found many examples about Jwt, but there is a place I don't understand.
找了很多关于Jwt的例子,但是有一个地方看不懂。 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 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创建令牌: 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资料: 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.在这里,我收到 argv 变量未定义的警告,我无法调用您创建的令牌。 After creating the token, I need to be able to call it without using a cookie or session.
创建令牌后,我需要能够在不使用 cookie 或 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.
注意:当 register_argc_argv 被禁用时,此变量不可用。
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):您可以在配置中启用它,或者使用我推荐的
$_SERVER
superglobal ,因为它不受配置差异的影响并且始终有效(包括 CLI):
$jwt = $_SERVER['argv'][1];
Same for $argc
. $argc
相同。
Use the following instruction to check what you get as arguments:使用以下说明检查您得到的 arguments:
<?php
var_dump($argv);
?>
From the official documentation, this is available as well as: $_SERVER['argv']
.从官方文档中,这也可用:
$_SERVER['argv']
。
Please also note that $argv
and $argc
need to be declared global, while trying to access within a class method.另请注意,
$argv
和$argc
需要声明为全局,同时尝试在 class 方法中访问。
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),然后,您需要从命令行 (CLI) 运行脚本,即:
php <script_name> argc1 arg2...
,如果您使用浏览器或 API 调用,您将能够从那里获取参数值,您需要使用 HTTP 方法(GET/POST),
Or with a JSON receiving call:或使用 JSON 接收呼叫:
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):如果在文件脚本中生成令牌,并且需要将其发送回不同的页面,则需要使用 GET/POST 请求,如果用户提供了值并且需要保存或使用它,则需要用一种方法接收它,下面是一个关于您的代码如何正常工作的示例(可以提供多种方法):
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 REST API PHP 中的身份验证示例 – Z1D1FADBD9150349C135781140FFFEED
https://www.codeofaninja.com/2018/09/rest-api-authentication-example-php-jwt-tutorial.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.