I have some PHP script that logs in and returns a JSON array with a session ID if the login was successful.
In my app, I want to login at the front page and continue out through the app being logged in. I created a singleton class that holds a session ID (along with a few other fields) received from the JSON from the PHP page. This singleton object’s field “session_id” gets checked depending on what the user does.
If the user wants to log out, then the session_id just gets set to null thus logging out.
I also use the HttpURLConnection library to POST the username/password when logging in.
Is this a decent enough approach for handling this situation?
Here are some things you should think about:
- Once you have authenticated the user and stored the session_id locally, send the session_id in the header of each of your http requests. That way, you’re not sending the credentials with each request, but the session id. And if something happens on the server side to the session, the transaction will not be allowed.
- When logging out, don’t just delete the session_id on your app (client) side. Send a logout to the server as well so that the session can be killed server side.
- If the session is killed on the server side, you’ll want to do 1 of 2 things A) prompt the user to re-login. B) Use the store credentials to log back in, create a new session id and store it again in your singleton.
This will guarantee a bit more security and functionality than just clearing the session id on your app side.
This strategy will probably work. In an app I worked on, I stored the return data from login in the android shared preferences. If the user logged out, I cleared the preferences. This allowed users to stay logged in, even if they closed the app and went back in later. I had an authentication token that I checked to see if the user’s login was still valid.
How do you plan on handling persisted logins? Does the sessionID expire? You might want to think about these situations otherwise once a user is logged in, they will be logged in forever or as long as the app is open.