I want in my API response when token expired it will return message “token expired” with status code 419, and when token invalid return “Unauthenticated” with status 401.
How can I do that?
I only use the basic of usage laravel sanctum, and I expect I can custom the response of Laravel sanctum when it expired token different with invalid token.
you can use middleware for this logic and create a middleware and in handle function :
public function handle(Request $request, Closure $next)
{
if (Auth::guard('sanctum')->guest()) {
throw new AuthenticationException('Unauthenticated.');
}
// if token is expired
if (Auth::guard('sanctum')->user()->tokenCan('expired')) {
return response()->json(['message' => 'Token expired'], 419);
}
// if token is invalid
if (Auth::guard('sanctum')->user()->tokenCan('invalid')) {
throw new UnauthorizedException('Unauthenticated.');
}
return $next($request);
}
and if using laravel 11 add this middleware in bootstrap/app.php
for a specific route.