How to create secure authentication tokens and not make the use login everytime?

Hello,

I followed many guides and learned how to make a simple web API using this awesome framework.
The only problem i am facing right now is how to create an authentication token that will identify each request and map it to a user.

Currently i have this authentication method which takes an apiKey value from the DB and return the details if the key exists.

public function authenticate($apikey)
{
    $user = Customers::where('apikey','=',$apikey)->take(1)->get();
    if(!isset($user[0]))
    {            
        return false;
    }

    $this->details=$user[0];
    return ($user[0]->exists) ? true:false;
}  

I can generate this random key and store it in the DB with an expiration date as the following:
$tokenValue = bin2hex(openssl_random_pseudo_bytes(8)); //generate a random token $tokenExpiration = date('Y-m-d H:i:s', strtotime('+1 hour'));//the expiration date will be in one hour from the current moment

there are 2 problems with this approach:
1 - there is a possibility of repeated key in the DB which will mix the orders and might get another user instead.
2- I will need to refresh this token often by making the users sign in everytime which is understandable for a website or web application but not for mobile app.

I don’t require high security like banks or sensitive data systems , but i would like to make the app secure and quick to use at the same time.

Can someone kindly guide me to the best approach to handle this problem?

one way i can think of is to store the Email and password locally and try to login automatically and get the a fresh token if it’s expired.

this might solve the second problem. but what about the first problem?
What are the chances of creating a repeated token?
Currently , i don’t have big list of customers so i can check if the token generated is already there in the DB but what if i have big number of customers?

“store the Email and password locally” doesn’t sound like a good idea from a security perspective.

This question is more about generic authentication and security of an API rather than specific to Slim. Therefore, you may find more helpful answers in places like stackoverflow. With that said, my own view is that there are so many considerations and easy mistakes with auth that I would never try to build my own.

There are a good number of well audited auth packages out there, for example thephpleague/oauth2-server which includes PSR-7 middleware that can be dropped into Slim. An alternative might be Auth0. They’ve already figured out issues surrounding collision of keys, resuming sessions, reissuing tokens, etc.

That’s just my view.

1 Like

I have found different middlewares for authentication but most of them were complex and not well documented.
I will try your suggestions.
Thanks a lot tfight.