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

when authentication fails! #250

Open andreclicksul opened 9 months ago

andreclicksul commented 9 months ago

Hello, forgive my English... I'm using slim 4 and raintpl, authenticating through cookies. Route authentication is perfect. My problem is when authentication fails, I need to redirect to the login route and I don't see how. I tried putting a "header("Location: /login/301")", but it didn't work.

Could you help me, please?

use \Dotenv\Dotenv;
use \Slim\Factory\AppFactory;
use \Click\Model\User;
use \Click\middlewares\authenticateMiddleware;

$env = Dotenv::createImmutable(__DIR__);
$env->load();

$app = AppFactory::create();

$app->addErrorMiddleware(true, true, true); 

$app->add(authenticateMiddleware::jwtAuth());
<?php

namespace Click\middlewares;

use \Psr\Http\Message\ResponseInterface as Response;
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Tuupola\Middleware\JwtAuthentication;

class authenticateMiddleware 
{
  public static function jwtAuth(): JwtAuthentication
  {
    return new JwtAuthentication([
      "secure"  => true,
      "relaxed" => ["localhost"],
      "path"    => ["/admin"],
      "cookie"  => "tkn",
      "secret"  => getenv('JWT_SECRET'),
      "error" => function ($response, $arguments) {
        $data["status"] = "error";
        $data["message"] = $arguments["message"];
        header("Location: /login/301");
      }
    ]);
  }
}
?>
mbolli commented 8 months ago

Try it like this:

return new JwtAuthentication([
      "secure"  => true,
      "relaxed" => ["localhost"],
      "path"    => ["/admin"],
      "cookie"  => "tkn",
      "secret"  => getenv('JWT_SECRET'),
      "error" => function ($response, $arguments) {
          // create request to route
          $requestFactory = new DecoratedServerRequestFactory(new ServerRequestFactory());
          $newRequest = $requestFactory->createServerRequest('GET', '/login/301');

          // internal redirect: needs $app in context
          return $app->handle($newRequest)->withStatus(301);
      }
    ]);

You would need to pass App $app to the jwtAuth() method.