Customize laravel sanctum unauthorize response
Asked Answered
G

4

8

I am using laravel sanctum in my project, but I am facing a problem. I want to customize the 401 response code (unauthorized) to return a JSON when a token is invalid, something like this:

    {
    "data": {
        "code": 401,
        "book": null,
        "success": false,
        "error": {
            "message": "Not authenticated"
        }
    }
}

Instead of default response:

{
    "message": "Unauthenticated."
}

How to achieve this in laravel sanctum? Thanks in advance.

Glare answered 25/7, 2021 at 7:0 Comment(0)
B
29

Rendering exceptions

Add to ExceptionHandler@register app/Exceptions/ExceptionHandler.php

$this->renderable(function (\Illuminate\Auth\AuthenticationException $e, $request) {
    if ($request->is('api/*')) {
        return response()->json([
            'message' => 'Not authenticated'
        ], 401);
    }
});
Buddhism answered 25/7, 2021 at 8:10 Comment(0)
D
3

You can override the Authenticate.php middleware to output the message you want OR catch the AuthorizationException to display the message you want in the Exception/Handler

public function render($request, Exception $exception)
{
    if ($exception instanceof AuthorizationException) {
        return response()->json([
         'message' => 'Not authenticated'
        ],401);
    }

    return parent::render($request, $exception);
}
Dialogist answered 25/7, 2021 at 7:35 Comment(3)
Where to put render function?Glare
i think he means there app/Http/Middleware/Authenticate.phpBuddhism
\Illuminate\Auth\AuthenticationException not AuthorizationExceptionStromboli
T
2

Since the release of Laravel 11, the approach is little bit different than the Juan's answer. Now this should be handled in withExceptions() method at bootstrap/app.php file.

->withExceptions(function (Exceptions $exceptions) {
    $exceptions->render(function (AuthenticationException $e, Request $request) {
        if ($request->is('api/*')) {
            return response()->json([
                'message' => 'Not authenticated'
            ], 401);
        }
    });
})
Thirtytwo answered 26/5 at 8:27 Comment(0)
C
1

Laravel 11.x full code bootstrap/app.php

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        //
    })
    ->withExceptions(function (Exceptions $exceptions) {
        // custom response sanctum
        $exceptions->render(function (AuthenticationException $e, Request $request) {
            if ($request->is('api/*')) {
                return response()->json([
                    'message' => 'Not authenticated'
                ], 401);
            }
            // Handle other exceptions or default response here
            return $e->render($request);
        });
    })->create();
Crosby answered 3/8 at 19:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.