Customize Laravel Passport response unauthenticated

后端 未结 3 439
臣服心动
臣服心动 2021-01-14 05:50

Currently I have a login, register, update and delete functionality using my api made in Laravel using passport feature. Everything works fine the insertion of data and fetc

相关标签:
3条回答
  • 2021-01-14 06:07

    This solution worked for me, found in the Laravel Docs. You can override the unauthenticated function in the Handler like this:

    protected function unauthenticated($request, AuthenticationException $exception)
    {
        return $request->expectsJson()
                    ? response()->json(['message' => $exception->getMessage()], 401)
                    : redirect()->guest(route('login'));
    }
    

    then, handle and provide the response you want.

    Don't forget to import this as well in the Handle.php file:

    use Illuminate\Auth\AuthenticationException;
    

    I hope it does work well for you!

    0 讨论(0)
  • 2021-01-14 06:12

    Override auth:api middleware, and modify it accordingly to give the response you want.

    0 讨论(0)
  • 2021-01-14 06:16

    Here's how I solved it. If you are using Laravel 5.5 or above you can override the default exception handler by editing app/Exceptions/Handler.php to add the following:

    use Illuminate\Auth\AuthenticationException;
    
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            $json = [
                'isAuth'=>false,
                'message' => $exception->getMessage()
            ];
            return response()
                ->json($json, 401);
        }
        $guard = array_get($exception->guards(),0);
        switch ($guard) {
            default:
                $login = 'login';
                break;
        }
        return redirect()->guest(route($login));
    }
    

    In the JSON return, you can add any parameters per your requirement.

    0 讨论(0)
提交回复
热议问题