Search code examples
phplaravelauthenticationaccess-tokenlaravel-passport

Laravel Passport: auth:api behaving like auth:web


I am trying to implement passport in my application to authenticate the api calls. I have done the configuration as mentioned in the official documentation. I have this in my auth guard:

'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],

And, this in my AuthServiceProvider's boot() method:

Passport::routes();

And this is the route I am trying to access:

    Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::group(['namespace' => 'Api', 'middleware' => 'auth:api'], function () {
    // Login Controller
   Route::get('/getclc', 'PreController@getClc');
});

I am sending the header in the request like this:

Authorization:Bearer $accessToken

My question is: 1. When a protected route is requested, it sends me to login page, but I want it to return the 401. How can I do that?

My laravel version is 5.4.33.


Solution

  • When authentication fails, Laravel throws an AuthenticationException exception. This exception is handled by your Laravel exception handler, and eventually calls the unauthenticated() method in your app/Exceptions/Handler.php file.

    You can see from that method that if your request expects a json response, you'll get a 401 Unauthenticated response. However, if you're not expecting a json response, it just redirects to the route named "login". This will obviously fail if you don't have a route named "login".

    Your request "expectsJson" when you send either the "X-Requested-With: XMLHttpRequest" header, or the "Accept: application/json" header. Otherwise, it is considered a normal web request.

    If you'd like to change how your application handles unauthenticated users, the unauthenticated() method is the one to change.