swatantra
swatantra

Reputation: 493

how to customize laravel passport respone on token expire

how to chage laravel passport response on access_token expire from

{
    "message": "Unauthenticated."
}

to

{
    "type": "error",
    "status": 401,
    "message": "Access Token expires",
}

Upvotes: 1

Views: 1240

Answers (2)

Amir Khan
Amir Khan

Reputation: 193

The accepted answer is correct but there is one more use case in monolith based application where you want to handle different responses based on api or web call.

Updated Code Snippet, you can tweek it according to your needs.

if ($exception instanceof TokenMismatchException) {
    if ($request->expectsJson()) {
         return response()->json([
               'message' => $exception->getMessage(),
               'error_code' => 'TOKEN_MISMATCH', // Custom code for identification
         ], $exception->getCode());
    } else {
         return redirect()->intended('login')->withErrors(['auth' => $exception->getMessage()]);
    }
}

OR one can combine both functions as follow:

use Illuminate\Auth\AuthenticationException;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Throwable;

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Throwable  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Throwable $exception)
{
    // Handle AuthenticationException
    if ($exception instanceof AuthenticationException) {
        if ($request->expectsJson()) {
            return response()->json([
                'type' => 'error',
                'status' => Response::HTTP_UNAUTHORIZED,
                'message' => 'Authentication failed or token expired.'
            ], Response::HTTP_UNAUTHORIZED);
        } else {
            return redirect()->guest(route('login'));
        }
    }

    // Handle TokenMismatchException
    if ($exception instanceof TokenMismatchException) {
        if ($request->expectsJson()) {
            return response()->json([
                'message' => $exception->getMessage() ?? 'CSRF token mismatch.',
                'error_code' => 'TOKEN_MISMATCH'
            ], Response::HTTP_FORBIDDEN);
        } else {
            return redirect()->back()->withErrors(['csrf_error' => 'Page expired, please try again.']);
        }
    }

    // Default handler for other exceptions
    return parent::render($request, $exception);
}

Upvotes: 0

mrhn
mrhn

Reputation: 18956

You can add custom exception handling in your App\Exceptions\Handler.php class. Add the following function if not already present. You are basicly catching the Authentication exception, and adding your own transformation to it.

use Illuminate\Http\Response;
use Illuminate\Auth\AuthenticationException;

public function render($request, Throwable $e)
{
    if ($e instanceof AuthenticationException) {
        return response()->json(
            [
                'type' => 'error',
                'status' => Response::HTTP_UNAUTHORIZED,
                'message' => 'Access Token expires',
            ],
            Response::HTTP_UNAUTHORIZED
        );
    }

    return parent::render($request, $e);
}

Upvotes: 4

Related Questions