3

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.

daninthemix
  • 2,542
  • 8
  • 29
  • 40
  • Best possible way is to use redis for faster access. Rest everything is fine. It depends upon the hits you will be receiving if traffic is less mysql is okay – Bugfixer Jan 20 '17 at 10:03

1 Answers1

0

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.