【问题标题】:Can't access token stored in container无法访问存储在容器中的令牌
【发布时间】:2017-06-24 20:28:06
【问题描述】:

我按照说明使用回调函数 (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);
}

【问题讨论】:

标签: jwt slim


【解决方案1】:

您的路由定义抛出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
)

【讨论】:

    【解决方案2】:

    您链接到的指令指出:

    只有在认证成功时才会调用回调。它接收 参数中的解码标记。如果回调返回布尔值false 强制认证失败。

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

    【讨论】:

    • 谢谢!令牌收到正确,我没有通过这条路线。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 2012-07-18
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多