我正在使用Slim Framework开发带有JSON Web Token的REST API,然后使用Postman进行测试。我已经创建了数据库连接,我在Postman中测试了GET,POST,PUT,DELETE,一切正常,现在我来到JWT身份验证。请记住,基本Http身份验证也可以正常工作。所以,代码
的.htaccess
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
customers.php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
$app = new \Slim\App;
$container = $app->getContainer();
$container["jwt"] = function ($container) {
return new StdClass;
};
$app->add(new \Slim\Middleware\JwtAuthentication([
"path" => "/api",
"passthrough" => ["/api/token", "/admin/ping"],
"secure" => true,
"environment" => "HTTP_X_TOKEN",
"header" => "X-Token",
"secret" => "supersecretkeyyoushouldnotcommittogithub",
"callback" => function ($request, $response, $arguments) use ($container) {
$container["jwt"] = $arguments["decoded"];
},
"error" => function ($request, $response, $arguments) {
$data["status"] = "error";
$data["message"] = $arguments["message"];
return $response
->withHeader("Content-Type", "application/json")
->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
}
]));
$app->add(function($request, $response, $next) {
$token = $request->getQueryParams()["token"];
if (false === empty($token)) {
$request = $request->withHeader("Authorization", "Bearer {$token}");
}
return $next($request, $response);
});
//Get All Customers
$app->get('/api/customers', function(Request $request, Response $response){
$sql = "SELECT * FROM customers";
try{
//Get DB Object
$db = new db();
// Connect
$db = $db->connect();
$stmt = $db->query($sql);
$customers = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($customers);
$fp = fopen('empdata3.json', 'w');
fwrite($fp, json_encode($customers));
fclose($fp);
header("Location: https://www.pawebgate.com/slimapp3/public/empdata3.json");
die();
}
catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
});
//Get Specific Customer
$app->get('/api/customer/{id}', function(Request $request, Response $response){
$id = $request->getAttribute('id');
$sql = "SELECT * FROM customers where id = $id";
try{
//Get DB Object
$db = new db();
// Connect
$db = $db->connect();
$stmt = $db->query($sql);
$customer = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($customer);
}
catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
});
你能帮我解决一下如何设置Postman以测试上述功能,或者我为了实现JWT Auth而必须采取的其他步骤吗?我总是得到“在邮差中找不到令牌”谢谢
首先,您需要创建一个获取令牌的路由,如下所示:
$app->post('/auth/token', function(Request $request, Response $response, array $args) {
$data = $request->getParsedBody();
$email = $data['email'] ?? null;
$password = $data['password'] ?? null;
/*[select logic here]*/
$user = $db->query("SELECT * FROM customers WHERE email = $email AND password = $password")...
/*[select logic here]*/
if($user){
$key = 'supersecretkeyyoushouldnotcommittogithub';
return $response->withJson([
'token' => JWT::encode($user, $key)
]);
}
return $response->withJson(['status' => 'error'], 401);
});