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?