我正在创建一个简单的社交媒体项目,以熟悉程序中的JWT交互 . 我的前端是Angular 6,我的后端包含在XAMPP(localhost服务器)上运行的PHP和MySql . 在我的前端遇到JWT拦截器时,它一直很顺利 . 拦截器的目标是在授权头中的每个api调用中将JWT附加到存储中 . 它正在完成所有这些,但它似乎使发送到服务器端代码的对象无效 . (我还应该注意,我所有的服务器端代码都可以通过邮递员进行测试 . )
这是我的拦截器的代码:
import { HttpInterceptor, HttpRequest, HttpEvent, HttpHandler } from
"@angular/common/http";
import { Observable } from "rxjs";
export class JwtInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next:HttpHandler): Observable<HttpEvent<any>> {
//intercepts any outgoing http request to add the jwt token to the header if it exists. else do not (server will handle if it is not included).
const token = JSON.parse(localStorage.getItem('token'));
if (token) {
const cloned = request.clone({
headers: request.headers.set("Authorization",
"Bearer " + token)
});
return next.handle(cloned);
}
return next.handle(request);
}
}
这是获取请求的服务器端php代码:LoginUser.php
<?php
// required headers
header("Access-Control-Allow-Origin: *");
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");
// includes to access the data we want to.
include_once '../config/Database.php';
include_once '../models/User.php';
// connect to the database.
$database = new Database();
$conn = $database->connect();
// create an instance of a user object.
$user = new User($conn);
// get the posted data
$data = json_decode(file_get_contents("php://input"));
$user->username = $data->username; // where I am getting an error message.
$user_exists = $user->userExists();
// generate json web token
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;
// verify user exists and the password is correct.
if($user_exists && password_verify($data->password , $user->password)){
$token = array (
"iss" => $iss,
"aud" => $aud,
"iat" => $iat,
"nbf" => $nbf,
"exp" => $exp,
"data" => array(
"username" => $user->username,
"accessLevel" => $user->accessLevel,
"email" => $user->email,
"isVerified" => $user->isVerified
)
);
// set the response
http_response_code(200);
// generate the jwt
$jwt = JWT::encode($token, $key);
echo json_encode(
array(
"message" => "Successful login.",
"jwt" => $jwt
)
);
}
else {
// set response code
http_response_code(401);
// tell the user login failed
echo json_encode(array("message" =>"Incorrect Login information." ));
echo json_encode(array("api call input" => $data));
}
按顺序发送请求将返回以下控制台输出:
从'http:// localhost:4200'访问来自'http://localhost/MySocialMedia/api/LoginUser.php'的XMLHttpRequest已被CORS策略阻止:对预检请求的响应未通过访问控制检查:它没有HTTP ok状态 .
当我去看网络响应时,结果如下:
<b>Notice</b>: Trying to get property 'username' of non-object in
<b>C:\xampp\htdocs\MySocialMedia\api\LoginUser.php</b> on line <b>26</b>
{"message":"Incorrect Login information."}{"api call input":null}
(为了这个例子的目的,当前报告空回声的第二个回应响应 json_encode($data)
. )基于这种行为,我会很快假设我只是没有正确准备发布请求,但是当我修改只是在没有克隆或添加承载令牌的情况下处理请求的拦截器,我得到了预期的输出:
{"message":"Incorrect Login information."}{"api call input":{"username":"incorrectAccount","password":"incorrectPassword"}}
从早先的错误消息我假设它可能与服务器端的CORS策略有关,但是我在头文件中设置了授权,但是,我不明白这可能是什么问题;在邮递员我能够附加一个授权 Headers ,仍然得到预期的行为 . 所有这些让我相信,在附加了承载令牌之后问题必须在拦截器内发生,但是我无法弄清楚到底出了什么问题 .
任何帮助将不胜感激!
此外,如果这可能有任何额外帮助,我让控制台注销请求和克隆请求的样子 . 除了具有映射数组“authorization”=>(我的jwt here)的克隆请求之外,它们看起来完全相同 .