0

I followed the instructions to save token in container with callback function (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));
    }
]));

No data is returned in response, it seems $this->jwt is empty.

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

function getUsers($req, $res, $args) {
    $decode = $this->jwt;
    print_r($decode);
}
robert
  • 797
  • 3
  • 9
  • 23
  • Possible duplicate of [Access $this inside a route in slim3 doesn't work "Using $this when not in object context"](http://stackoverflow.com/questions/40362978/access-this-inside-a-route-in-slim3-doesnt-work-using-this-when-not-in-objec) – jmattheis Feb 07 '17 at 17:26

2 Answers2

1

The instruction you linked to states:

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

Do you meet this requirement when testing, i.e do you authenticate successfully? Also consider using var_dump($decode) instead of print_r($decode) when testing.

Georgy Ivanov
  • 1,573
  • 1
  • 17
  • 24
1

Your route definition throws Using $this when not in object context error. To have access to $this you need to use a closure instead. See closure binding in the documentation.

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

or

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

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

With the either of code above you can access decoded token via $this. First example is preferred.

$ 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
)
Mika Tuupola
  • 19,877
  • 5
  • 42
  • 49