I have this code running on every HTTP request:
if ($request->header('Authorization')) {
$token = $request->header('Authorization');
$user = User::where('api_token', $token)->whereRaw("`api_token_expires` >= CURDATE()")->active()->first();
if ($user) {
$GLOBALS['user_id'] = $user->id;
$GLOBALS['is_admin'] = $user->admin;
return $next($request);
}
}
As you can see, I'm hitting the database for every request looking for a valid API token.
What's a more efficient - but safe, best practice - way of handling this? Should I be looking at MySQL caching? Redis or something else?
EDIT: I'm not using sessions, this is a stateless API.
You can make api-users authorize first and respond with a session token.
Then they can use this session token for each next request.
You can store these sessions in the $_SESSION variable, on disk in a file or on a fast database like Redis.
To do this securely I would remove old sessions automatically, check the session token against it's origin IP, and force https for the api.