具有JWT身份验证和Postman的Slim框架

具有JWT身份验证和Postman的Slim框架,jwt,postman,slim,Jwt,Postman,Slim,我正在使用Slim框架开发一个带有jsonweb令牌的restapi,然后用Postman进行测试。我已经创建了数据库连接,我在Postman中测试了GET、POST、PUT、DELETE,一切正常,现在我开始使用JWT身份验证。请记住,基本Http身份验证也可以正常工作。那么,代码 .htaccess RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}] customers.php use \Psr\Http\Mess

我正在使用Slim框架开发一个带有jsonweb令牌的restapi,然后用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);
});
然后,您可以复制响应并在Postman中发出POST请求,将令牌添加到标题“Authorization”中。

您是否尝试在postman中设置
X-Token
http头?嗨Daniel O,你能说得更具体一点吗?我读了你的链接,但不知道怎么做。请按步骤设置: