How to change laravel sanctum return "message": "Unauthenticated."
Asked Answered
A

2

5

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 ^^

Assembler answered 16/3, 2022 at 15:19 Comment(0)
O
13

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

Oscar answered 16/3, 2022 at 15:44 Comment(2)
Thank you very much. This works perfectly. Knowing the right place to make the change is key in laravel. :)Embodiment
any one using this , don't forget to import the AuthenticationException class in order for it to workAlain
N
3

For latest Laravel 11, you can update the app.php inside the bootstrap folder with following code,

use Illuminate\Auth\AuthenticationException;

And change the withException with following code

->withExceptions(function (Exceptions $exceptions) {
    $exceptions->render(function (AuthenticationException $e, Request $request) {
        $response['statusCode'] = 403;
        $response['message'] = 'Unauthorized';
        return response()->json(['error' => true, 'content' => 'YOUR MESSAGE']);
    });
})
Normy answered 5/5, 2024 at 6:57 Comment(1)
Yep, confirming. Just updated it in Laravel 11! Thanks!Newish

© 2022 - 2025 — McMap. All rights reserved.