我有一些用于接收和发布php中数据的API ,我想保护它们。因此,我正在研究和实现JWT
,这是我的Auth类
include_once '../config/core.php';
include_once '../libs/php-jwt-master/src/BeforeValidException.php';
include_once '../libs/php-jwt-master/src/ExpiredException.php';
include_once '../libs/php-jwt-master/src/SignatureInvalidException.php';
include_once '../libs/php-jwt-master/src/JWT.php';
use \Firebase\JWT\JWT;
// generate jwt will be here
$token = array(
"iss" => $iss,
"aud" => $aud,
"iat" => $iat,
"nbf" => $nbf,
"data" => array(
"id" => "secretKey"
)
);
$jwt = JWT::encode($token,$key);
echo json_encode(
array( "message" => "succesful login",
"jwt" => $jwt
));
此代码为我提供了JWT
令牌。现在进行身份验证,我有这个类
header("Access-Control-Allow-Origin: http://localhost/rest-api-authentication-example/");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// required to decode jwt
include_once 'config/core.php';
include_once 'libs/php-jwt-master/src/BeforeValidException.php';
include_once 'libs/php-jwt-master/src/ExpiredException.php';
include_once 'libs/php-jwt-master/src/SignatureInvalidException.php';
include_once 'libs/php-jwt-master/src/JWT.php';
use \Firebase\JWT\JWT;
// retrieve gieve jwt here
$data = json_decode(file_get_contents("php://input"));
$jwt = isset($data->jwt) ? $data->jwt : "";
if($jwt){
try{
echo strtotime(time()."+4 hour");
$decoded = JWT::decode($jwt ,$key,array('HS256'));
echo json_encode(array(
"message" => "Access granted",
"data" => $decoded->data
));
}
// if decode fails, it means jwt is invalid
catch (Exception $e){
// set response code
//http_response_code(401);
// tell the user access denied & show error message
echo json_encode(array(
"message" => "Access denied.",
"error" => $e->getMessage()
));
}
}
// show error message if jwt is empty
else{
// set response code
//http_response_code(401);
// tell the user access denied
echo json_encode(array("message" => "Access denied."));
}
现在,我不知道如何强加令牌验证来检查是否有人要从URL获取或发布数据。假设我有这个网址
CMSApp/Api/postdata.php
如何验证使用的令牌有效?请记住,不需要用户名或密码。