mardi 20 août 2019

Handle AuthenticationException in Laravel API

I developed a project in Laravel 5.4 which has API and Web requests. I need to handle AuthenticationException. If it is a web request I need to redirect to the login page. If it an API call then I need to return an error message. So I Implemented the code like this

in app/Exception/Handler.php

public function render($request, Exception $exception)
{

    if ($exception instanceof TokenMismatchException) {

        //return redirect()->back()->with('message', 'Security token expired. Please, repeat your request.');
        return redirect()->route('logout');
    }

    if($exception instanceof \Illuminate\Auth\AuthenticationException ){
        return response(['error' => 'unauthorized'], 401);
    }

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

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }


    return redirect()->guest(route('login'));
}

But Always I get 'error' => 'unauthorized' everywhere (web and API). But in web, It wants to redirect to the login page. Could anyone help me to solve the issue?

laravel/passport=~4.0 



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2NgtU3n
via IFTTT

Aucun commentaire:

Enregistrer un commentaire