Skip to content
Advertisement

Secure way for PHP REST api?

I am developing the PHP based REST api. I have android app which will send some key parameters to server and the server will respond with the data. In this case, the email is the key element to get all the relevant data. If I want to make it secure, I can save password in sharedPreferences and send it at every request. This might make communication secure, but I understand that sharedPreferences are not secure and putting confidential information in them is not recommended. Also, I cannot store a hash of password in sharedPreferences because I am using the password_hash() function in php api which requires password as plain text. So, i have to send request as a plain text password only. What should I do to make it secure?

Advertisement

Answer

There’s the normal way things like this are done and that is usually with some form of token authentication.

However, you probably want to learn more about security except what you’re doing is a toy app only you intend using. With that being said, PHP is very wonderful at handling sessions, so you can consider using a cookie jar in your app and take advantage of sessions. REST purists will probably hang me for that suggestion, but you know what? It works perfectly provided you’re gonna be using your API for just your app.

Another quick and easy solution is to do a normal email and password login from your app. On success, return a randomly generated token to the user and also store in a table on your database. This token is what you can store in sharedpref that will be sent along with every request. To make things more interesting, you can allow the token expire after say 10 minutes if it hasn’t been used. On your app this will mean the user needs to login again, and generate a new token.

If you’re going with the token generation model, you wanna make sure the token is not easily guessable. I usually just use something like this for those kind of random alphanumeric strings:

$randomLongString = hash('sha384', microtime() . uniqid() . bin2hex(random_bytes(10)));

For the expiry, you can record the timestamp the token table was accessed, store it in a column with the same token. If the old timestamp + (expiry time) > timestamp now, then you know the token is expired. Return a 401. If not update the old timestamp with the current timestamp, then return a 200.

These are relatively simple but effective solutions that work for single server setups, and relies on the fact that the user is still the same user. Other things you could do is IP checking, device ID verification before you generate the token. And if any of those things change along the way, you quickly invalidate the token and provide a way for the user to prove they are who they claim they are.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement