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

问题描述 投票:1回答:2

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

还有一个骨架项目,它将为您提供示例应用程序的快速入门,因此,如果您只是想要工作而不是探索所有移动部件的工作原理,请使用它。

在现实生活中,很难整合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:未经授权

enter image description here

php json authentication jwt slim
2个回答
1
投票

你误解了参数secret。它不是令牌。它是您用于签名令牌的密钥。

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

use Firebase\JWT\JWT;

$payload = [
    "sub" => "[email protected]"
];
$token = JWT::encode($payload, "thisissecret", "HS256");

在使用JWT之前,最好先阅读这篇introduction


0
投票

1. Generate Token

使用firebase/php-jwt

$payload = [
    "sub" => "[email protected]"
];
    $token = JWT::encode($payload,'JWT-secret-key');

2. .htaccess Changes

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

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

3. Middleware

$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. Correct Request

enter image description here

5. Wrong Token Request

enter image description here

Reference Link

© www.soinside.com 2019 - 2024. All rights reserved.