Home > OS >  How to change laravel sanctum return "message": "Unauthenticated."
How to change laravel sanctum return "message": "Unauthenticated."

Time:03-18

I have integrated sanctum for API authentication. I was facing a problem of redirection if the token is unauthenticated and solved it using this answer on laracasts

I could get a JSON response like:

{
"message": "Unauthenticated."
}

What I am trying to do is to handle this response to be something like:

{
"status_code": 401,
"success":false,
"message": "Unauthenticated."
}

Thanks in advance ^^

CodePudding user response:

If you check the source code of laravel/sanctum at this line

 if (! $request->user() || ! $request->user()->currentAccessToken()) {
    throw new AuthenticationException;
 }

they use the AuthenticationException so you could overwrite it by using Rendering Exceptions by adding the register method in your App\Exceptions\Handler like this

use Illuminate\Auth\AuthenticationException;

public function register()
{
  $this->renderable(function (AuthenticationException $e, $request) {
    if ($request->is('api/*')) {
        return response()->json([
          'status_code' => 401,
          'success' => false,
          'message' => 'Unauthenticated.'
        ], 401);
    }
   });
}

you cloud read more about Rendering Exceptions in the docs

  • Related