我是苗条的新人。我在共享主机上使用slim框架,我正在尝试使用JWT身份验证中间件对我的Web服务进行身份验证。我能够生成令牌成功,但无法验证它。能帮我解决这个问题吗?
这是我的app.php
自举/ app.php
<?php session_start();
require __DIR__ .'/../vendor/autoload.php';
use Tuupola\Middleware\HttpBasicAuthentication;
use Firebase\JWT\JWT;
use Tuupola\Base62;
$app = new \Slim\App([
'settings' => [
'displayErrorDetails' => true,
'addContentLengthHeader' => false,
'logger' => [
'name' => 'slim-app',
'path' => __DIR__ . '/../logs/app.log',
'level' => \Monolog\Logger::DEBUG,
]
]
]);
$container = $app->getContainer();
$container['renderer'] = function ($c) {
$settings = $c->get('settings')['renderer'];
return new Slim\Views\PhpRenderer($settings['template_path']);
};
$container['logger'] = function ($c) {
$settings = $c->get('settings')['logger'];
$logger = new Monolog\Logger($settings['name']);
$logger->pushProcessor(new Monolog\Processor\UidProcessor());
$logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], $settings['level']));
return $logger;
};
$container['logger'] = function($c) {
$logger = new \Monolog\Logger('my_logger');
$file_handler = new \Monolog\Handler\StreamHandler("../logs/app.log");
$logger->pushHandler($file_handler);
return $logger;
};
$container["jwt"] = function ($container) {
return new StdClass;
};
$app->add(new \Slim\Middleware\JwtAuthentication([
"path" => "/",
"logger" => $container['logger'],
"secret" => "123456789_my_secret",
"rules" => [
new \Slim\Middleware\JwtAuthentication\RequestPathRule([
"path" => "/",
"passthrough" => ["/token", "/sign-up"]
]),
new \Slim\Middleware\JwtAuthentication\RequestMethodRule([
"passthrough" => ["OPTIONS"]
]),
],
"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(new \Slim\Middleware\HttpBasicAuthentication([
"path" => "/api/token",
"users" => [
"user" => "password"
]
]));
$app->add(new \Tuupola\Middleware\Cors([
"logger" => $container["logger"],
"origin" => ["*"],
"methods" => ["GET", "POST", "PUT", "PATCH", "DELETE"],
"headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"],
"headers.expose" => ["Authorization", "Etag"],
"credentials" => true,
"cache" => 60,
"error" => function ($request, $response, $arguments) {
return new UnauthorizedResponse($arguments["message"], 401);
}
]));
$app->post("/token", function ($request, $response, $args) use ($container){
$requested_scopes = $request->getParsedBody() ?: [];
$now = new DateTime();
$future = new DateTime("+10 minutes");
$server = $request->getServerParams();
$jti = (new Base62)->encode(random_bytes(16));
$payload = [
"iat" => $now->getTimeStamp(),
"exp" => $future->getTimeStamp(),
"jti" => $jti,
"sub" => '123456789_my_secret'
];
$secret = "123456789_my_secret";
$token = JWT::encode($payload, $secret, "HS256");
$data["token"] = $token;
$data["expires"] = $future->getTimeStamp();
return $response->withStatus(201)
->withHeader("Content-Type", "application/json")
->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
});
$app->get("/dashboard", function ($request, $response, $args) {
$data = ["status" => 1, 'msg' => "This is dashboard"];
return $response->withStatus(200)
->withHeader("Content-Type", "application/json")
->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
});
$app->get("/sign-up", function ($request, $response, $args) {
$data = ["status" => 1, 'msg' => ":)"];
return $response->withStatus(200)
->withHeader("Content-Type", "application/json")
->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
});
的index.php
<?php
if (PHP_SAPI == 'cli-server') {
// To help the built-in PHP dev server, check if the request was actually for
// something which should probably be served as a static file
$url = parse_url($_SERVER['REQUEST_URI']);
$file = __DIR__ . $url['path'];
if (is_file($file)) {
return false;
}
}
require __DIR__.'/bootstrap/app.php';
$app->run();
的.htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
</IfModule>