Up please
Thanks !
Hello everyone,
I'm currently using Laravel 11 and I use sanctum for authentication.
When i don't pass any Bearer Token i have the redirection to the Login page through AuthenticationException, that's the normal workflow from sanctum.
As my Laravel project will be only for API i would like to return a custom Json response. I know that i can pass the "Accept : application/json" in the Header request to return the default sanctum error Json but i would like to always return my custom JSON without passing "Accept : application/json" in the Header.
My question : How can I override the default workflow when AuthenticationException is raised by Sanctum ? I tried by creation a custom Exception and also in the bootstrap/app.php but nothing works.
bootstrap/app.php ->
use Illuminate\Auth\AuthenticationException;
->withExceptions(function (Exceptions $exceptions) {
$exceptions->stopIgnoring(AuthenticationException::class);
$exceptions->render(function (AuthenticationException $exception, Request $request) {
//Unauthorized
return response()->json([
'message' => 'Unauthorized action',
'custom_field' => 'My new field'
], 401);
});
Thank very much !
Please or to participate in this conversation.