tuupola / slim-basic-auth

PSR-7 and PSR-15 HTTP Basic Authentication Middleware
MIT License
440 stars 66 forks source link

Add request object back to the error handler. #95

Open tuupola opened 4 years ago

tuupola commented 4 years ago

Add request object back as parameter to the error handler.

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "error" => function ($request, $response, $arguments) {
      ...
    }
]));

See https://github.com/tuupola/branca-middleware/pull/13 for reference.

joelmora commented 3 years ago

@tuupola FYI I did a workaround on v3.3.1 to be able to throw a Slim HTTP code.

use Slim\Exception\HttpUnauthorizedException;

  // 1st middleware to configure basic authentication
  $app->add(new HttpBasicAuthentication([
    "users" => [
      "root" => "secret",
    ],
    "error" => function ($response) {
      return $response->withStatus(401);
    }
  ]));

  // 2nd middleware to throw 401 with correct slim exception
  $app->add(function (Request $request, RequestHandler $handler) {
    $response = $handler->handle($request);
    $statusCode = $response->getStatusCode();

    if ($statusCode == 401) {
      throw new HttpUnauthorizedException($request);
    }

    return $response;
  });

any other way to get the request object?

MarcHagen commented 1 year ago

Changing the processError function in HttpBasicAuthentication would give the desired result. Passing the $request through to the use to do whatever.

    private function processError(ServerRequestInterface $request, ResponseInterface $response, array $arguments): ResponseInterface
    {
        if (is_callable($this->options["error"])) {
            $handler_response = $this->options["error"]($request, $response, $arguments);
            if ($handler_response instanceof ResponseInterface) {
                return $handler_response;
            }
        }
        return $response;
    }

We can PR this, but that would be breaking for older installations. Don't know if there is a major/minor coming out soon?

As intermit step, adding a option to throw an Exception instead would also give the desired effect.

tuupola commented 1 year ago

Yeah cannot break BC. A kludgish workaround would be to include the request object in the second parameter which is an array.

4.x version is planned but since I recently started freelancing paid work comes first atm.