MiddlewareInterface question regarding practices with auth


Fairly new to middleware concept and start to feel confortable with delegation MiddlewareInterface::process(), but what’s the recommended way to handle error responses (unauthorized, redirect response, content-types…) ?

For example:

class JwtAuthMiddleware implements ServerMiddlewareInterface
    public function process(ServerRequestInterface $request, DelegateInterface $delegate): ResponseInterface
        $auth = $this->authenticate($jwtToken=?, $login=?, $password=?);
        if ($auth->isValid()) {
           $response = $delegate->process($request->withAttribute('xxxx', $auth));
           return $response;

       // Not authenticated - my question is about this:
       switch($type) {
           case 'json':
                return new JsonResponse(['message' => 'unauthorized'], 401);
          // case 'xml': ...
                return new RedirectResponse('/login');       

Is there a recommended approach for doing this ? (ErrorResponse, UnauthorizedResponse factory ?)

PS: an early WIP example code: https://github.com/belgattitude/soluble-wallit/blob/99b91f50694b5f165ea7c60b0bf451991a20f399/src/Soluble/Wallit/JwtAuthMiddleware.php#L79

First and foremost, check with the docs on how to handle errors. Basically, If you want to use the “built-in” error handling, you should include Zend\Stratigility\Middleware\ErrorHandler at the front of your app pipeline and throw exceptions in your middleware. For instance, I’m using a bearer token (similar to what I see above) from the request header. One of the sections I have in my token service:

$authHeader = $request->getHeader('Authorization');
if (!$authHeader) {
    throw new InvalidArgumentException('Authorization Header Not Found', StatusCode::STATUS_UNAUTHORIZED);

The exception will be caught by ErrorHandler. You can add listeners (logging, etc) and an error generator to the ErrorHandler object via a factory to help handle creating the JSON/XML/HTML response.


Edit: Clarify where to add listeners and error message generator.

Thanks @moderndeveloperllc, was not aware of that

1 Like

@belgattitude Glad to help. I’ve been rewriting an app off and on for the past handful of months into an Expressive 1, then Expressive 2 implementation. Once you get into the flow, it’s a nice, minimalist framework. Good luck on your project!