他们说,这是我第一次使用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:未经授权
你误解了参数secret
。它不是令牌。它是您用于签名令牌的密钥。
由您决定如何生成令牌。例如有online tool。您还可以使用PHP生成令牌。
use Firebase\JWT\JWT;
$payload = [
"sub" => "[email protected]"
];
$token = JWT::encode($payload, "thisissecret", "HS256");
在使用JWT之前,最好先阅读这篇introduction。
$payload = [
"sub" => "[email protected]"
];
$token = JWT::encode($payload,'JWT-secret-key');
如果使用Apache,请将以下内容添加到.htaccess文件中。否则PHP将无法访问Authorization:Bearer标头
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
$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));
}
]));