无法访问存储在容器中的令牌

Can't access token stored in container

我按照说明使用回调函数将令牌保存在容器中 (https://github.com/tuupola/slim-jwt-auth):

$app = new \Slim\App();

$container = $app->getContainer();

$container["jwt"] = function ($container) {
    return new StdClass;
};

$app->add(new \Slim\Middleware\JwtAuthentication([
    "path" => ["/"],
    "passthrough" => ["/version", "/auth"],
    "secret" => "mysecret",
    "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));
    }
]));

响应没有返回数据,好像$this->jwt是空的。

$app->get("/user", 'getUsers');

function getUsers($req, $res, $args) {
    $decode = $this->jwt;
    print_r($decode);
}

您链接到的说明:

Callback is called only when authentication succeeds. It receives decoded token in arguments. If callback returns boolean false authentication is forced to be failed.

您在测试时是否满足此要求,即是否认证成功?还可以考虑在测试时使用 var_dump($decode) 而不是 print_r($decode)

您的路线定义引发 Using $this when not in object context 错误。要访问 $this 您需要使用闭包。请参阅文档中的 closure binding

$app->get("/user", function ($request, $response, $arguments) {
    $decode = $this->jwt;
    print_r($decode);
});

$getUsers = function ($request, $response, $arguments) use ($container) {
    $decode = $this->jwt;
    print_r($decode);
};

$app->get("/user", $getUsers);

使用以上任一代码,您都可以通过 $this 访问已解码的令牌。第一个例子是首选。

$ curl --include http://localhost:8081/user --header "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.mHEOMTUPhzNDAKheszd1A74EyLmKgy3PFdmKLg4ZNAE"
HTTP/1.1 200 OK
Host: localhost:8081
Connection: close
X-Powered-By: PHP/7.0.12
Content-Type: text/html; charset=UTF-8
Content-Length: 84

stdClass Object
(
    [sub] => 1234567890
    [name] => John Doe
    [admin] => 1
)