1

I really appreciate it if someone can help me here. Is there a way I can call the endpoint that generates the api jwt token within my container, anytime the last one expires? below is auth part of my container

App::class => function (ContainerInterface $container) {
        
        AppFactory::setContainer($container);

        $app = AppFactory::create();
      
        $app->add(new Tuupola\Middleware\JwtAuthentication([
            "secret" => $_ENV['JWT_SECRET'],
            "ignore" => ["/api/token","/users"], //s
            "error" => function ($response, $arguments) {
                $data["status"] = "error";
                $data["message"] = $arguments["message"];
                //$app->post('/api/token', \App\Action\ApiAuthAction::class)->setName('user-api');
                 return $response
                    ->withHeader("Content-Type", "application/json")
                    ->getBody()->write((string)json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)); 
            }
        ]));
        return $app;
    },

This is my auth file

public function __invoke(ServerRequestInterface $request, ResponseInterface $response, array $args = []): ResponseInterface
    {


        $userData = $this->userReader->findUserByEmail($request->getParsedBody());
        if ($userData) {
            $now = new DateTime();
            $future = new DateTime($_ENV['JWT_EXPAIRED'] . " minutes");
            $jti = (new Base62)->encode(random_bytes(16));
            $payload = [
                "iat" => $now->getTimeStamp(),
                "exp" => $future->getTimeStamp(),
                "jti" => $jti,
                "sub" => $userData->email
            ];

            $secret = $_ENV['JWT_SECRET'];
            $token = JWT::encode($payload, $secret, "HS256");
            $data["token"] = $token;
            $data["expires"] = $future->getTimeStamp();
            $response->getBody()->write((string)json_encode([
                'success' => true,
                'message' => $token
            ]));
        } else {
            $response->getBody()->write((string)json_encode([
                'success' => false,
                'message' => 'Invalid Email or Password'
            ]));
        }

        return $response->withHeader('Content-Type', 'application/json')->withStatus(200);
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
chized
  • 23
  • 1
  • 6
  • Since you're verifying the token on each request, can't you just check the expire date then and update it if it's less than x amount of time left? If it already has expired, they should need to authenticate themselves again anyway. Personally, I would let it expire and force the users to authenticate again (depending on what expire time you've set, that is) – M. Eriksson Oct 03 '22 at 14:25

0 Answers0