Jake Wilson
Jake Wilson

Reputation: 91193

Android - How to do MySQL db transactions using authentication?

For databases that don't require any sort of username or password, I normally fetch data from a MySQL db from my Android app by accessing PHP scripts. To send data to the database I send GET or POST variables to PHP scripts.

But if I need to access a database that would normally require a web user to login first, how would I interact with the database? In my Android app, the user would specify his login and password.

PHP Sessions?

Can Android apps somehow use PHP sessions when accessing PHP scripts on some web server via HTTP requests?

Send Login/Password as GET/POST params?

In my app, when accessing my PHP scripts, do I send the login and password as GET/POST parameters every time I want to access restricted data? Seems kinda sketchy sending login/password as GET/POST every time.

Auth token?

Or would I send the login/password once to authenticate and then retrieve some sort of token that I would send on subsequent calls to the PHP script? I would envision it working like this:

  1. User sends login info to PHP script
  2. After authentication is successful, random token is generated and placed in user table.
  3. Token is sent back to app
  4. Subsequent database calls include the token as a GET/POST parameter.
  5. PHP script uses token to authenticate user and fetch database info that is restricted to that user.

A couple things about this approach:

  1. When does the app log the user out? When he exits the app? When he switches to a different app? When the activity is destroyed?
  2. If the user does not manually log out of the app (which would normally clear the token value from the user table), when does the token value get cleared?
  3. What happens if the user shuts off his phone and looses connection to the database? Should the database automatically clear the token value from the user table after some period of time so that some random lucky individual couldn't guess the token?
  4. Should the token also set some sort of last_accessed_at timestamp and deny authentication using the token after a certain period of time?

There are dozens of tutorials out there for accessing MySQL web databases using Android apps, but I can't find any that discuss working with credentials and/or authentication schemes.

Upvotes: 0

Views: 826

Answers (1)

Adam Fowler
Adam Fowler

Reputation: 1751

Remember that sessions are normally tracked using a cookie. All you would have to do is save that cookie and use it in your headers when making requests from your android app, and then you have a working session.

Also look into doing a special handshake or using some special kind of security. Never trust the input!

Upvotes: 1

Related Questions