tuupola / slim-jwt-auth

PSR-7 and PSR-15 JWT Authentication Middleware
https://appelsiini.net/projects/slim-jwt-auth
MIT License
827 stars 141 forks source link

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

Open ShivPandey opened 5 years ago

ShivPandey commented 5 years ago
$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));
    }
]));
dakujem commented 5 years ago

@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).

LeonardoYoel commented 3 years ago

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...

dakujem commented 3 years ago

@LeonardoYoel What about the use keyword...

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

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

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

dakujem commented 3 years ago

@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.