mariovalney / laravel-keycloak-web-guard

Simple Keycloak Guard to Laravel Web Routes - https://packagist.org/packages/vizir/laravel-keycloak-web-guard
146 stars 80 forks source link

Expired token throw [Keycloak Error] User cannot be authenticated #21

Closed ygiraud closed 4 years ago

ygiraud commented 4 years ago

When I reopen a page containing Auth::hasRole('XXX') with an expired token I've got a an exception "[Keycloak Error] User cannot be authenticated" (throwed by vendor/vizir/laravel-keycloak-web-guard/src/Auth/Guard/KeycloakWebGuard.php:133).

Is it possible to handle expired tokens (and redirect the user to login route) keeping the exception for authentication errors?

Thanks

mariovalney commented 4 years ago

Well... If user received a RefreshToken we handle it and save a new token.

Can you provide the steps to reproduce your issue? I'll check here.

Thanks

ygiraud commented 4 years ago

Sure:

mariovalney commented 4 years ago

_A note: this exception will show only if APPDEBUG is true. If not, will procced if false and consider user not logged.

With that in mind, I check here and the token was refreshed successfully. My access token has a lifespan of 1 minute.

My case:

It's ok, since refresh token expired.

--

So I'll close this as seems everything is OK. If you have any questions, let me know :)

mintalicious commented 10 months ago

Hi, I know this issue is already closed, but I am facing this behavior while in debug mode (dev environment). Is there a way to let the guard behave like in prod although debug is on? When testing locally and demonstrating my app, this exception might not be very helpful, since it should be correct and normal to redirect when Keycloak's session has expired.

Thx

mintalicious commented 8 months ago

I solved this by implementing a middleware which fetches the thrown KeycloakCallbackException and redirects the user to the login page.

    public function handle(Request $request, Closure $next): Response
    {
        /**
         * @var \Illuminate\Http\Response
         */
        $resp = $next($request);

        if (!empty($resp->exception) && $resp->exception instanceof KeycloakCallbackException) {
            if ($request->wantsJson()) {
                abort(419);
            } else {
                return redirect()->route('keycloak.login');
            }
        }

        return $resp;
    }