robsontenorio / laravel-keycloak-guard

🔑 Simple Keycloak Guard for Laravel
MIT License
434 stars 141 forks source link

Invalid Token Response Status Code #25

Closed chrismeyers closed 4 years ago

chrismeyers commented 4 years ago

When I make a request to a route guarded by the keycloak middleware with an invalid bearer token, such as with an expired token or invalid resource_access, the response status code is set to 500. I'd expect this to be a 401 instead since the problem is related to being unauthorized, not an internal error. I think this behavior may lead to confusion, especially when Laravel's APP_DEBUG is disabled in production environments. In that case only the following is returned:

Status: 500 Internal Server Error

{
    "message": "Server Error"
}

I did some experimenting and if the KeycloakGuardException extends from Illuminate\Auth\AuthenticationException instead of \UnexpectedValueException, a 401 will be returned.

Is this normal behavior or is there some configuration I'm missing? I apologize if I'm missing something obvious, I'm new to Laravel. Any help would be greatly appreciated!

chrismeyers commented 4 years ago

I apologize, this isn't a problem. It was just my lack of Laravel experience showing. App\Exceptions\Handler::render() can be modified to handle specific exceptions like:

use KeycloakGuard\Exceptions\KeycloakGuardException;
use Illuminate\Http\Response;

...

public function render($request, Throwable $exception)
{
    if ($exception instanceof KeycloakGuardException) {
        return response()->json(
            ['error' => $exception->getMessage()],
            Response::HTTP_UNAUTHORIZED
        );
    }

    return parent::render($request, $exception);
}

Documentation: https://laravel.com/docs/7.x/errors#render-method