我在用于登录的php类中具有此功能:
public function login($conn, $user, $password){
try{
$login = "SELECT username FROM login WHERE username=:user LIMIT 1";
$execLogin = $this->conn->prepare($login);
$execLogin->bindValue(":user", $user);
$execLogin->execute();
$res = $execLogin->rowCount();
$fetch = $execLogin->fetch();
if($res>0)
{
//Check Password and Generate a token
$checkPassword = "SELECT login_id, username, user_privilige
FROM login
WHERE
username = :user
AND
password = :pass
LIMIT 1";
$execCheckPassword = $this->conn->prepare($checkPassword);
$execCheckPassword->bindValue('user', $user);
$execCheckPassword->bindValue('pass', $password);
$execCheckPassword->execute();
$fetchRes = $execCheckPassword->fetch();
$resFound = $execCheckPassword->rowCount();
//Then
if($resFound>0)
{
//Generate a JWT
//Array to generate a JWT from
$arrayJWT =
[
'login_id'=>$fetchRes['login_id'],
'username'=> $fetchRes['username'],
'user_role'=>$fetchRes['user_privilige']
];
$encodedJWT = JWT::encode($arrayJWT, $this->key);
$resArray =
[
'jwt'=> $encodedJWT,
'user_exist'=> 'true',
'user_id'=>$fetchRes['login_id'],
'username'=> $fetchRes['username'],
'user_role'=>$fetchRes['user_privilige']
];
$_SESSION['jwt']=$encodedJWT;
}
else
{
$resArray = ['user_exist'=> 'false', 'errorMsg' => "Incorrect Password!!!"];
}
}
else
{
$resArray = ['user_exist'=> 'false', 'errorMsg' => "Username doesn't exist"];
}
return $resArray;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
在此功能中,我正在生成一个JWT,将其发送回Angular并将其保存在本地存储中。
以下是单击登录按钮时,angular将向此代码发送凭据:
<?php
require_once('../api.php');
//Getting username and password from Angular
$user = $_POST['username'];
$password = $_POST['password'];
$newApi = new api();
$conn = $newApi->connection();
$res = $newApi->login($conn, $user, $password);
echo json_encode($res);
?>
如果您看到,在主功能中,如果登录成功,我就设置了会话:
$_SESSION['jwt']=$encodedJWT;
如果我var_dump它,它将清晰显示
现在,当用户尝试访问组件时,我需要检查他是否有权使用防护措施来执行此操作。这个问题的目的不是。
PHP Api的另一个功能:
public function checkLoginAdmin($conn, $jwt, $sessionJWT)
{
try
{
$sessionJWT = $_SESSION['jwt'];
//var_dump($this->sessionJwt);
if($sessionJWT !== "")
{
$decodedJWT = JWT::decode($jwt, $this->key, array('HS256'));
$jwtRole = $decodedJWT->user_role;
if($sessionJWT==$jwt && $jwtRole=="admin")
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
如果您已经注意到,我正在使用一个新变量将会话加入其中:
$sessionJWT = $_SESSION['jwt'];
现在,当用户尝试访问组件时,此函数将调用其专用的api函数:
<?php
require_once('../api.php');
session_start();
//Getting JWT
$jwt = $_POST['jwt'];
$sessionJWT = $_SESSION['jwt'];
var_dump($_SESSION);
//Result of var_dump is null
$newApi = new api();
$conn = $newApi->connection();
$res = $newApi->checkLoginAdmin($conn, $jwt, $sessionJWT);
echo json_encode($res);
?>
如果我var_dump
的会话值将为null,这就是什么都不起作用的原因。
因此,当调用登录功能时,一切正常,当我调用checkLoginAdmin()时,会话将被破坏。
P.S。我在班级顶部开始了一个课程。
编辑
我刚刚尝试使用$_COOKIE
,它的行为相同。