Search code examples
phpapirestauthenticationbasic-authentication

PHP - RESTful API for mobiles with authentication


I found many questions/answers here and many articles in other websites but I have still a few questions which I need to answer before I can start and I just can't find answers for them. I want to create restful api for mobile apps (and for some frontend).

I choose Basic Authentication via HTTPS because I guess it's enough for now and it looks easy to implement. So I should have username and hashed password saved in dabatase right? Then when user write username and password in app I hashed password and both encrypt by Base64 and add to HTTP header right? How can I decrypt this and check with database on server-side? How it would change with salt?

And after I check username and password with previous call then how can I save this session? Should I create some session-id/token (random string) and save it to column in users table and send it back to mobile app and then using it for other calls (with some timestamp for expiration)? Could it be via HTTP (no secure)? Like web.com/api?token=ASsF234Silkj&data=... Or I must always use HTTPS after authentication?

How will it change when I use some API key (private) in all apps which would use this API? I know I can hide key and don't send it via requests (use it just for encryption) but what if someone try to read .apk and get API key?


Solution

  • First off, base64 is not encryption

    While it is possible to integrate basic http authentication with sessions it is not a trivial task. And it's very easy to end up with something which is insecure (especially judging from the level of skill evidenced in your question).

    You seem to have planned out most of what you want to acheive - but you've got most of it wrong already.

    Whether you should continue to use HTTPS after authentication depends if your service has any intrinsic value.

    Similarly how you implement surrogate authentication tokens (including API keys) depeds on the security model. Stick to using HTTPS everywhere and you should not have to worry about changing / encrypting the API key.