Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Respond with status code 401 on authentication failure using Laravel and Passport?

I'm configuring a Laravel project to use Passport token authentication. Everything seems to be working, but when the auth:api middleware fails, it responds to the client with a status of 200 and a bunch of HTML in the response body. Instead, I want it to respond with a status of 401.

I can't find anything in the Laravel Passport source or documentation about doing something like this. I can't even find the source for the middleware.

My test route:

Route::get('/protected', function () {
    return response()->json([
        'success' => true
    ]);
})->middleware('auth:api');

config/auth.php

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

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

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],

    'appUsers' => [
        'driver' => 'eloquent',
        'model' => App\Models\AppUser::class
    ],
],
like image 641
SimpleJ Avatar asked Mar 07 '17 19:03

SimpleJ


2 Answers

You can solve it by sending this header with your request.

Accept : application/json

This will send this message with 401 status code.

{
    "message": "Unauthenticated."
}
like image 143
Ariful Haque Avatar answered Sep 17 '22 08:09

Ariful Haque


If a user does not authenticate, Laravel will throw an AuthenticationException.

This exception is handled by the render method in Illuminate/Foundation/Exceptions/Handler.php, and will in turn call the the unauthenticated() method which is defined in your app/Exceptions/Handler.php:

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

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

As you can see, by default, if the request expects a JSON response, you'll get a 401 with a JSON error body. If the request does not expect JSON, the request is redirected to the login page.

The expectsJson() method will return true if your request has either the Accept: application/json header, or the X-Requested-With: XMLHttpRequest. The Accept: application/json header is more appropriate for api calls, whereas the X-Requested-With: XMLHttpRequest header is used for ajax calls.

So, without changing any of your application code, just make sure the requests include the Accept: application/json header.

However, if you need to have a different action happen when a user is not authenticated, you can modify this unauthenticated() method in app/Exceptions/Handler.php:

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

    // return a plain 401 response even when not a json call
    return response('Unauthenticated.', 401);
}
like image 22
patricus Avatar answered Sep 19 '22 08:09

patricus