robsontenorio / laravel-keycloak-guard

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

Invalid token always returns code 500 #115

Closed mobieljoy12 closed 1 month ago

mobieljoy12 commented 4 months ago

Hi,

I've recently started using this package in order to integrate keycloak into some Laravel applications I'm working on. What I have noticed however, is that whenever the key is not valid or has expired, the middleware returns the 500 status code. The message does display what has happened, but this means my client does not know how to deal with errors, as they all return the same code.

vdeville commented 3 months ago

Hello, I have the same behavior, when user doesn't have resource_access the bundle return 500 not 401 Thanks

mobieljoy12 commented 3 months ago

Hi @vdeville , I have written a fix and will submit a pull request when back from my holidays. Till then though, feel free to write a general exception handler in the Handler class within Laravel. Handle the TokenException to return a 401 response and you should have the result you are looking for.

https://laravel.com/docs/11.x/errors

vdeville commented 3 months ago

Hello, Yes i add this in bootstrap/app.php

    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->render(function (\KeycloakGuard\Exceptions\ResourceAccessNotAllowedException | \KeycloakGuard\Exceptions\TokenException $e, Request $request) {
            return response()->json([
                'message' => $e->getMessage()
            ], Response::HTTP_UNAUTHORIZED);
        });
    })

Thanks