Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

aliraza108's avatar

Custom API auth token miss match error

I've built a custom api authentication system. I've checked laravel passport but it's too much for me.

So here's the following middleware which I'm using for token verification:

<?php

namespace App\Http\Middleware;

use Closure;
use Validator;
use App\Token;
Use Carbon\Carbon;

class VerifyToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $access_token = $request->access_token;

        $tokenData = Token::where('access_token', $access_token)->orderBy('id', 'desc')->first();

        if (is_null($tokenData)) {
            return response()->json(['status' => false, 'error' => 'Token Not Matched for User, Unauthorized Access.'], 401);
        }

        $now = Carbon::now();

        if ($now->gte(Carbon::createFromFormat('Y-m-d H:i:s', $tokenData['expires_at']))) {
            return response()->json(['status' => false, 'error' => 'Expired Token. Kindly Get another Token'], 401);
        }

        return $next($request);
    }
}

So the problem is it works fine for one or two requests with the valid token. But after that it starts giving token mismatch error. The token exists in the database and also not expired but it keeps giving mismatch error.

Sometime for every request I've to get a new token. So can anyone help me with what's wrong with the code?

0 likes
1 reply
aurawindsurfing's avatar

Hi,

I would say that your problem is not related to your middleware. You do not have token mismatch exception here so it is not coming from here.

The most common is csrf token mismatch exception problem which is completely different to your token. I would say that this is source of your issue.

More about it here: https://laravel.com/docs/master/csrf

Happy coding!

Please or to participate in this conversation.