簡體   English   中英

我無法使用 jwt 驗證用戶

[英]I can't verify user with jwt

我正在嘗試使用 Jwt 進行身份驗證。 找了很多關於Jwt的例子,但是有一個地方看不懂。 我可以使用庫輕松生成令牌,但我無法驗證這里是我使用的庫

composer require firebase/php-jwt

我正在創建一個令牌

   // 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);

創建令牌: 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"}

資料: http://www.ismailcakir.com/jwt/test2.php?action=stuff

在這里,我收到 argv 變量未定義的警告,我無法調用您創建的令牌。 創建令牌后,我需要能夠在不使用 cookie 或 session 的情況下調用它。 我嘗試了很多方法,但我無法理解如何服用。

根據文檔

注意:當 register_argc_argv 被禁用時,此變量不可用。

最有可能是你的情況。 您可以在配置中啟用它,或者使用我推薦的$_SERVER superglobal ,因為它不受配置差異的影響並且始終有效(包括 CLI):

$jwt = $_SERVER['argv'][1];

$argc相同。

使用以下說明檢查您得到的 arguments:

<?php
var_dump($argv);
?>

從官方文檔中,這也可用: $_SERVER['argv']

另請注意, $argv$argc需要聲明為全局,同時嘗試在 class 方法中訪問。

為了能夠獲得令牌:

$ _SERVER ['argv'] [1]

然后,您需要從命令行 (CLI) 運行腳本,即: php <script_name> argc1 arg2... ,如果您使用瀏覽器或 API 調用,您將能夠從那里獲取參數值,您需要使用 HTTP 方法(GET/POST),

或使用 JSON 接收呼叫:

file_get_contents("php://input");

似乎您將所有內容都放入了代碼中,您的代碼需要重新編寫。

如果在文件腳本中生成令牌,並且需要將其發送回不同的頁面,則需要使用 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);

你可以看看:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM