Certainly! The issue here is that Laravel's auth:sanctum middleware will always reject expired tokens, regardless of any custom middleware you add before or after it. This is by design for security reasons. So, if you want to allow expired tokens for certain routes (like logout), you cannot use auth:sanctum on those routes.
Solution: Custom Middleware as Authenticator
Instead of stacking accept-expired-token and auth:sanctum, replace auth:sanctum with your custom middleware for that route. Your custom middleware should handle all authentication logic, including expired tokens.
1. Register your middleware in app/Http/Kernel.php:
protected $routeMiddleware = [
// ...
'accept-expired-token' => \App\Http\Middleware\Api\AcceptExpiredToken::class,
];
2. Update your route to use only your custom middleware:
Route::post('logout', [APKAuthController::class, 'logOut'])
->middleware('accept-expired-token');
3. In your controller, you can access the authenticated user:
public function logOut(Request $request)
{
$user = $request->user(); // Provided by your middleware
$token = $request->get('token');
$tokenExpired = $request->get('token_expired');
// Perform logout logic, e.g., delete the token
$token->delete();
return response()->json(['message' => 'Logged out successfully']);
}
Key Points
- Do not use
auth:sanctumon routes where you want to allow expired tokens. - Your custom middleware must handle all authentication and user resolution.
- For all other routes, continue using
auth:sanctumfor standard behavior.
Summary:
You can't "skip" or override auth:sanctum's expiration check from another middleware. Instead, use your custom middleware in place of auth:sanctum for routes where you want to allow expired tokens. This keeps your logic clear and secure.