Slim 3 PHP - 无法从 middleware.php 访问 settings.php 中的值

Slim 3 PHP - can't access values in settings.php from middleware.php

我有一个中间件,用于检查 JWT 令牌上的有效签名以获取对私有路由的 GET 请求。在其中,我需要提供存储在 ['settings']['jwt']['secret'] 的 settings.php 中的 JWT 秘密。我尝试使用 $this->settings->jwt->secret 访问此值并收到错误:

Using $this when not in object context

我切换到使用 $app->settings->jwt->secret 并收到错误

Uncaught InvalidArgumentException: Secret must be either a string or an array of "kid" => "secret" pairs



middleware.php

$app->add(new \Tuupola\Middleware\JwtAuthentication([
    "path" => "/api", /* or ["/api", "/admin"] */
    "attribute" => "decoded_token_data",
    "secret" => $this->settings->jwt->secret,
    "algorithm" => ["HS256"],
    "error" => function ($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));
    }, ]));

settings.php

return [
    'settings' => [
        'displayErrorDetails' => true, // set to false in production
        'addContentLengthHeader' => false, // Allow the web server to send the content-length header

        // Renderer settings
        'renderer' => [
            'template_path' => __DIR__ . '/../templates/',
        ],

        // Monolog settings
        'logger' => [
            'name' => 'slim-app',
            'path' => isset($_ENV['docker']) ? 'php://stdout' : __DIR__ . '/../logs/app.log',
            'level' => \Monolog\Logger::DEBUG,
        ],
        // database connection details
        "db" => [
            "host" => "127.0.0.1",
            "dbname" => "sity",
            "user" => "root",
            "pass" => "",
        ],

        // jwt settings
        "jwt" => [
            'secret' => 'jwtsecret',
        ],
    ],
];

访问该值(或 settings 对象中与此相关的任何内容)的正确方法是什么?

像这样的东西应该可以工作:

$modulesSettings = $this->get('settings')['jwt']['secret'];

根据文档 (http://www.slimframework.com/docs/v3/objects/application.html):

There are also a number of settings that are used by Slim. These are stored in the settings configuration key. You can also add your application-specific settings.

As the settings are stored in the DI container so you can access them via the settings key in container factories.

因此,在添加中间件之前,请继续获取设置,因为如错误所示,您不在对象上下文中。

$container = $app->getContainer();
$jwtSettings = $container->get('settings')['jwt'];

然后在 $app->add() 中你应该能够得到像这样的令牌:

"secret" => $jwtSettings['secret'],