tuupola / slim-jwt-auth

PSR-7 and PSR-15 JWT Authentication Middleware
https://appelsiini.net/projects/slim-jwt-auth
MIT License
821 stars 140 forks source link

setting header on error response does not work #218

Closed shorif2000 closed 2 years ago

shorif2000 commented 2 years ago

set the following

"error" => function ($response, $arguments) {
            $data = [
                'details' => [
                    'message' => 'Unauthorized',
                ],
                'message' => $arguments["message"]
            ];
            return $response
                ->withHeader('Access-Control-Allow-Origin', $_ENV['ALLOWED_DOMAINS'])
                ->withHeader(
                    'Access-Control-Allow-Headers',
                    'X-Requested-With, Content-Type, Accept, Origin, Authorization'
                )
                ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
                ->withHeader('Content-Type', 'application/json')
                ->getBody()->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
        }

trigger an expired request but none of the headers get set so I had to change it to

"error" => function ($response, $arguments) {
            $data = [
                'details' => [
                    'message' => 'Unauthorized',
                ],
                'message' => $arguments["message"]
            ];
            header("Content-Type: application/json");
            header("Access-Control-Allow-Origin: " . $_ENV["ALLOWED_DOMAINS"]);
            header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept, Origin, Authorization");
            header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS");
            return $response
                ->getBody()->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
        }
tuupola commented 2 years ago

The response object you pass to the error handler does not contain the headers. Try something like this instead:

"error" => function ($response, $arguments) {
    $data = [
        'details' => [
            'message' => 'Unauthorized',
        ],
        'message' => $arguments["message"]
    ];

    $response->getBody()->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));

    return $response
        ->withHeader('Access-Control-Allow-Origin', $_ENV['ALLOWED_DOMAINS'])
        ->withHeader(
            'Access-Control-Allow-Headers',
            'X-Requested-With, Content-Type, Accept, Origin, Authorization'
        )
        ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
        ->withHeader('Content-Type', 'application/json');
}