tuupola/slim-jwt-auth

There is any way to validate Token from database if failed return 403 through before => function(){}

ShivPandey opened this issue · 5 comments

$app->add(new Tuupola\Middleware\JwtAuthentication([
    "secret" => AUTH_KEY,
    "ignore" => ["/login", "/home"],
    "before" => function ($request, $arguments) {
        $token = $request->getAttribute("token");
        if($token){
            // define school global variable
            defined("TOKEN") || define("TOKEN", $token);

        } else {
            return false message
        }
    },
    "error" => function ($response, $arguments) {
        $data["status"] = "error";
        $data["message"] = $arguments["message"];
        return $response
            ->withHeader("Content-Type", "application/json")
            ->getBody()->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
    }
]));

@ShivPandey the before callback is not fired when an error occurs during the decoding. Instead, you can use the error callback to do whatever you want (including changing the status to 403 or doing something with your DB).

Hello. I have something similar and I have not been able to query my database when I get an error decoding the token. I am using Doctrine, I have a service where I perform the query to close the session, but in the constructor of the service I have to pass the container that contains entitymanager. That is precisely the problem, I cannot pass the container from the error function in the jwtauthentication middleware...

@LeonardoYoel What about the use keyword...

$container = $app->getContainer(); // for example

$app->add(new  JwtAuthentication ([
    'error' => function() use ($container){ $container->doStuff(); }
]));

I'm trying to handle throw new \Exception('unauthorized', 401); from before, is that possible?

@LeonardoYoel
Did you mean to do this?

    $slim->add(function (
        \Psr\Http\Message\ServerRequestInterface $request,
        \Psr\Http\Server\RequestHandlerInterface $handler
    ) {
        try {
            return $handler->handle($request);
        } catch (Throwable $e) {
            // report
            \Sentry\captureException($e);

            // rethrow (propagate)
            throw $e;
        }
    });

If you place this middleware on top of the JwtAuthentication middleware in the stack (that is, below in the code), it will catch anyting thrown by it, including the before callable.

This is getting seriously off-topic, though.