JWT 401:在 Slim 3 框架中未经授权

JWT 401: Unauthorized in Slim 3 framework

这是我第一次使用 slim 3 框架框架项目,他们说

There is also a skeleton project which will give you a quick-start for a sample application, so use that if you’d rather just have something working rather than exploring how all the moving parts work.

现实生活中很难融入JSON Web Token Authentication Middleware

我尝试按照教程中的步骤进行操作,但仍然无法正常工作。 请帮帮我?

这是我的代码

middleware.php

$app->add(new \Slim\Middleware\JwtAuthentication([
  "path" => "/",
  "passthrough" => "/test",
  "secret" => "thisissecret"
]));

和我的/路线

routes.php

$app->get('/',App\MemberController::class);

但结果如下图,401: Unauthorized

您误解了参数 secret。它是 而不是 令牌。它是您用来签署令牌的密钥

如何生成令牌由您决定。例如有一个 online tool。您还可以使用 PHP.

生成令牌
use Firebase\JWT\JWT;

$payload = [
    "sub" => "user@example.com"
];
$token = JWT::encode($payload, "thisissecret", "HS256");

在使用 JWT 之前阅读这篇文章是个好主意introduction

1。生成令牌

使用firebase/php-jwt

$payload = [
    "sub" => "user@example.com"
];
    $token = JWT::encode($payload,'JWT-secret-key');

2。 .htaccess 变化

如果使用 Apache,请将以下内容添加到 .htaccess 文件中。否则 PHP 将无法访问 Authorization: Bearer header

RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

3。中间件

$app->add(new \Slim\Middleware\JwtAuthentication([
    "path" => "/api",
    "passthrough" => ["/test"],
    "secret" => "JWT-secret-key",
    "secure" => false,
    "callback" => function ($request, $response, $arguments) use ($container) {
        $container["jwt"] = $arguments["decoded"];
    },
    "error" => function ($request, $response, $arguments) {
        $data["status"] = "0";
        $data["message"] = $arguments["message"];
        $data["data"] = "";
        return $response
        ->withHeader("Content-Type", "application/json")
        ->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
    }
]));

4。正确请求

5。错误的令牌请求

Reference Link

如果您使用的是 apache 服务器并通过 https 协议提供服务,那么您的 .htaccess 文件看起来像

RewriteEngine On
RewriteCond %{HTTPS} On
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L,QSA]

# Set the headers for the restful api
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "X-Requested-With, Content-Type, Accept, Origin, Authorization"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT, PATCH"