'How to change laravel sanctum return "message": "Unauthenticated."
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 ^^
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
