【问题标题】:Slim Framework with JWT Authentication and Postman带有 JWT 身份验证和 Postman 的 Slim 框架
【发布时间】: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? 我总是得到“在邮递员中找不到令牌” 谢谢

【问题讨论】:

标签: jwt postman slim


【解决方案1】:

首先,您需要创建一个获取 Token 的路由,如下所示:

$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 请求,将令牌添加到标头“授权”中。

【讨论】:

    猜你喜欢
    • 2017-05-18
    • 2015-11-16
    • 2019-03-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 2017-04-27
    • 2016-09-05
    相关资源
    最近更新 更多