5

I am using laravel sanctum in my project, but I am facing a problem. I want to customize the 401 response code (unauthorized) to return a JSON when a token is invalid, something like this:

    {
    "data": {
        "code": 401,
        "book": null,
        "success": false,
        "error": {
            "message": "Not authenticated"
        }
    }
}

Instead of default response:

{
    "message": "Unauthenticated."
}

How to achieve this in laravel sanctum? Thanks in advance.

Denny Kurniawan
  • 1,581
  • 2
  • 15
  • 28

2 Answers2

23

Rendering exceptions

Add to ExceptionHandler@register app/Exceptions/ExceptionHandler.php

$this->renderable(function (\Illuminate\Auth\AuthenticationException $e, $request) {
    if ($request->is('api/*')) {
        return response()->json([
            'message' => 'Not authenticated'
        ], 401);
    }
});
Juan Eizmendi
  • 984
  • 6
  • 10
3

You can override the Authenticate.php middleware to output the message you want OR catch the AuthorizationException to display the message you want in the Exception/Handler

public function render($request, Exception $exception)
{
    if ($exception instanceof AuthorizationException) {
        return response()->json([
         'message' => 'Not authenticated'
        ],401);
    }

    return parent::render($request, $exception);
}
Tayyab mehar
  • 648
  • 6
  • 8