dipeshkhanal79's avatar

dipeshkhanal79 liked a comment+100 XP

2mos ago

Sanctum override JSON Response (AuthenticationException)

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 !

dipeshkhanal79's avatar

dipeshkhanal79 wrote a reply+100 XP

4mos ago