Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

when authentication fails! #250

Open
andreclicksul opened this issue Dec 25, 2023 · 1 comment
Open

when authentication fails! #250

andreclicksul opened this issue Dec 25, 2023 · 1 comment

Comments

@andreclicksul
Copy link

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
Copy link

mbolli commented Jan 18, 2024

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants