JWT Auth Middleware Responce

Hi, Hoping someone could help me.

I am trying to implement some Auth Middleware on my api and am struggling to create a responce if the user is not authorised.

I am sending a JWT created in a react app using firebase, checking if it is valid and if the user is in the database.
I am struggling with the responce if the user is null. here is what I am trying. Any help would be great.
if the user is null it means the JWT was not vaild, or the user was not found in the database.

class AuthMiddleware
{
    public function __invoke(Request $request, RequestHandler $handler): Response
    {
        $user = validateFirebaseJWT($request);
        if ($user == null) {
            //throw new HttpForbiddenException($request);
            //throw new HttpUnauthorizedException($request, 'ERROR_401_API_KEY_MISSING');
            $response = new Response();
            $response->getBody()->write('Unauthorised Request');
            return $response->withStatus(403);
        }
        return $handler->handle($request);
    }
}

$app->add(new AuthMiddleware);

Thanks

Can you show the current exact error message?

Hey there,
Is it just that this is for an API so it needs to return a JSON response? If so would the following fix it for you?

class AuthMiddleware
{
    public function __invoke(Request $request, RequestHandler $handler): Response
    {
        $user = validateFirebaseJWT($request);
        
        if ($user == null)
        {
            //throw new HttpForbiddenException($request);
            //throw new HttpUnauthorizedException($request, 'ERROR_401_API_KEY_MISSING');
            $responseData = array('error' => 'Unauthorised Request');
            $response = new Response();
            $response->getBody()->write(json_encode($responseData));
            $response->withHeader('Content-Type', 'application/json');
            $response->withStatus(403);
        }
        else
        {
            $response = $handler->handle($request);
        }

        return $response;
    }
}

The key things are the setting of the content type to JSON, and the json_encoding of the body message.