【发布时间】:2018-07-03 09:38:22
【问题描述】:
我正在使用 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? 我总是得到“在邮递员中找不到令牌” 谢谢
【问题讨论】:
-
你试过在邮递员中设置
X-Tokenhttp 头吗? getpostman.com/docs/postman/sending_api_requests/… -
嗨,Daniel O,您能说得具体一点吗,我阅读了您的链接,但不知道该怎么做。请逐步设置