Search code examples
laravellaravel-passport

Laravel Passport to return 403 error instead of route('login')


I'm trying to get Laravel Passport to give clients a 403 response instead of a route('login') when they try to access a resource via REST with an invalid Authorization token.

This is my route/api.php

Route::middleware(['auth:api'])->group(function () {
    Route::prefix('invoices')->group(function () {
        Route::post('', 'API\InvoiceController@create');
    });
});

And this is my app/Http/Middleware/Authenticate.php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            //return route('login');
            return response()->json([],403);
        }
    }
}

However, the redirectTo gives the error Header may not contain more than a single header, new line detected.

I'm not sure where to set my 403 response?

I'm using Laravel 5.8.


Solution

  • To convert an authentication exception into an unauthenticated json response, you can override the unauthenticated method on /app/Exceptions/Handler.php.

    <?php
    
    namespace App\Exceptions;
    
    use Illuminate\Auth\AuthenticationException;
    // ...
    
    class Handler extends ExceptionHandler
    {
        // ...
            
        /**
         * Convert an authentication exception into an unauthenticated response.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Illuminate\Auth\AuthenticationException  $exception
         * @return \Illuminate\Http\Response
         */
        protected function unauthenticated($request, AuthenticationException $exception)
        {
            return response()->json(['error' => 'my custom message.'], 403);
        }
    }