How do I set up persistent authentication in a mobile app? - android

All sorts of mobile apps - Gmail, Facebook, Pandora - have some persistent mechanism of authentication that enables a user to set up credentials once and then use them to automatically authenticate with their remote service in the future. I'm probably blind, but I can't seem to find a tutorial anywhere out there that explains in simple terms how to properly do this on a mobile app.
How do I build this functionality? A link to a simple tutorial would be great.

As Deva said, SharedPreferences is a perfect quick and easy solution for creating this feature. Usually when I want to implement this I follow this simple flow:
Logging In:
When the user logs in save the user id (it can really be any unique identifier) into Shared Preferences. This information should now be available so that your app can recall it later
Rebooting:
When the app reboots it should check to see if any user id is saved in Shared Preferences. If not, then there is no one to automatically log in. If there is, then reload the user information using the user id from the server or whatever.
Logging Out:
When the user logs out make sure you delete the key/value pair from Shared Preferences.

For this probabely you can try a SharedPrefrence. The first time user enters his details , the values get stored locally if the user is authenticated and every consecutive time you can check the same prefrence if the value is already there directly pick the value and invoke the service for authentication.

Apple's KeyChain is service ment exactly for such a scenario. it enables a persistent, secure and easy to use storage.
Good tutorial (+ demo application) here

Related

Share Android shared preferences between different devices

I have an app, that on the first start generates a random user id and password to set up an account on my server and store them in the shared preferences.
I am looking for a way to write this data into the cloud so that if the user installs the app on a second device it will retrieve this account data and use them on the second device as well.
On iOS, this is a trivial task but I am still trying to figure out how to achieve this on Android. I tried an approach with Firestore, but it seems to be able to write to the Firebase database, the user has to log in with Firebase. I assumed being logged in to a Google Account on the device would do this, but I still get invalid permissions back when writing data.
I do not want to force the user to a separate login.
Any ideas on how to approach this task? Is it possible on Android at all?
I have an app, that on first start generates a random user ID and password to set up an account on my server and store them in the shared preferences.
If you have your own server where you authenticate the users, and you also want to authenticate to Firebase, then I recommend you check:
Custom Authentication System
I am looking for a way to write this data into the cloud so that if the user installs the app on a second device it will retrieve this account data and use them on the second device as well.
You just should never simply store the credentials in Firestore. Storing passwords in cleartext is one of the worst security risks you can inflict on your users. You should either use authentication with your custom system or use one of the existing providers, like Google, Facebook, etc.
I tried an approach with Firestore, but it seems to be able to write to the database, the user has to log in with Firebase.
It's recommended to authenticate the user in Firebase before reading/writing data from/to Firestore because you can secure your database using Firestore Security Rules.
P.S. Don't store data in ShartedPreferences because this type of data is stored locally and doesn't persist application uninstalls.

How do I enable secure user data access using Firebase without requiring user to login

Say I'm building some basic not-so-secure Android app, and I want to use firebase as a DB, but I really don't want the user to login. What would be my best choice of authentication?
If I allow "Annonymous" login - will this mean a big security hole, or would it just mean that programmatically I am allowed to change data anywhere in the db?
Does firebase support automatic creation/logging of user using my own custom user/id mechanism (without any user intervention)? Docs aren't very clear about that...
Anonymous log-in just provide authentication, that means you can associate a Unique ID to each of your user.
This de facto create a user ID and a Auth Token that is persisted in the phone between runs of your app. Token is refreshed when you call signInAnonymously().
Check this link for hits on how to handle anonymous logins.
Talking about security, anonymous login is not a bad practice. Obviously if you want to keep your DB safe you have to write custom access rules:
e.g. you probably want "anon_user322" to read your page content, but definitely not to modify or delete it.
Achieving this is not so hard, you have just to go to your FirebaseConsole and write your own rules for the Database.
You can find on this page a good starting guide. I suggest to watch this talk from Google I/O 2016, it is a bit long but you will be able to understand the basic of authentication and security in Firebase Database just with the first 25-30 minutes.
I was using annoymous sign in at first but it has somedown sides like you cannot export and import the exact same user on another device. Therefore i started using password authentication. You can just generate an pseudo email via uuid#yourappdomain.com and also generate the password and keep it within the appdata.
For security purpose you wont get around setting up rules for writing and reading data but it is working quite simple and easy enough to test with both methods annonymous and passoword auth.

Android:Storing username and password? [duplicate]

If I want to store the username and password to be used inside an Android application, what is the best way to do it? Is it through the preferences screen (but what if the user misses this?), or pop up a dialog box and ask the user for the credentials? If so, I do have to maintain state for the application. How would I do this?
Most Android and iPhone apps I have seen use an initial screen or dialog box to ask for credentials. I think it is cumbersome for the user to have to re-enter their name/password often, so storing that info makes sense from a usability perspective.
The advice from the (Android dev guide) is:
In general, we recommend minimizing the frequency of asking for user
credentials -- to make phishing attacks more conspicuous, and less
likely to be successful. Instead use an authorization token and
refresh it.
Where possible, username and password should not be stored on the
device. Instead, perform initial authentication using the username and
password supplied by the user, and then use a short-lived,
service-specific authorization token.
Using the AccountManger is the best option for storing credentials. The SampleSyncAdapter provides an example of how to use it.
If this is not an option to you for some reason, you can fall back to persisting credentials using the Preferences mechanism. Other applications won't be able to access your preferences, so the user's information is not easily exposed.
You should use the Android AccountManager. It's purpose-built for this scenario. It's a little bit cumbersome but one of the things it does is invalidate the local credentials if the SIM card changes, so if somebody swipes your phone and throws a new SIM in it, your credentials won't be compromised.
This also gives the user a quick and easy way to access (and potentially delete) the stored credentials for any account they have on the device, all from one place.
SampleSyncAdapter (like #Miguel mentioned) is an example that makes use of stored account credentials.
I think the best way to secure your credential is to first think of storing the Password with encryption in the account.db file which couldn't be easily available in non rooted devices and in case of rooted device the hacker must need the key to decrypt it.
Other option is do all your authentication like the way Gmail is doing. after the first authentication with the Gmail server . you got the Auth Token that would be use in case of your password . that token would be store in plain text.this token could be false in case you change the password from Server.
the last option I'd recommend you to enable 2-Factor Authentication & create Device Specific Password for your device. After losing device, all you need is to disable that device.
Take a look at What is the most appropriate way to store user settings in Android application if you're concerned about storing passwords as clear text in SharedPreferences.
You can also look at the SampleSyncAdapter sample from the SDK. It may help you.
Take a look at this this post from android-developers, that might help increasing the security on the stored data in your Android app.
Using Cryptography to Store Credentials Safely
With the new (Android 6.0) fingerprint hardware and API you can do it as in this github sample application.
These are ranked in order of difficulty to break your hidden info.
Store in cleartext
Store encrypted using a symmetric key
Using the Android Keystore
Store encrypted using asymmetric keys
source: Where is the best place to store a password in your Android app
The Keystore itself is encrypted using the user’s own lockscreen pin/password, hence, when the device screen is locked the Keystore is unavailable. Keep this in mind if you have a background service that could need to access your application secrets.
source: Simple use the Android Keystore to store passwords and other sensitive information
The info at http://nelenkov.blogspot.com/2012/05/storing-application-secrets-in-androids.html is a fairly pragmatic, but "uses-hidden-android-apis" based approach. It's something to consider when you really can't get around storing credentials/passwords locally on the device.
I've also created a cleaned up gist of that idea at https://gist.github.com/kbsriram/5503519 which might be helpful.

Facebook Session Destroyed after application closed

I have integrated Facebook with my android application. it is working good but when I close the application the session is destroyed and I have to login again .
I want to remain logged-in till the user clicks on logout button? How can I achieve that?
The key to this solution and the cause of the problem is likely found in the access token used. My guess is that you are currently using a short access token.
If you would use a long term access token, see, https://developers.facebook.com/docs/facebook-login/access-tokens/, and store it in a persistant manner the problem would be solved. Since you are using Android I would store it in SQLite and retrive upon application startup/resume.
From Facebook developer site:
Expiration and Extending Tokens
Some access tokens have a finite validity period of about one to two hours. In order to continue using these tokens after the expiry time, they need to be extended.
Apps using the Facebook SDKs for Android and iOS, desktop apps or apps using the server-side login flow automatically generate long-lived user access tokens. This long-lived token refreshes and extends each time the login flow is triggered. However, apps that implement their own client-side flow must implement some server side code to manually extend the tokens using a Graph API endpoint:
So if I were you, I would try to generate a long term access token of a relevant kind, store it an a persistant way (for example in a data base) and use it upon application start or resume.
Regards,
Jonas
As #Jonas karlsson said i want to add some point to it.
If you want, that the app should not ask for log-in again and again, When the app started you should use Persistent storage for that. Save the accessToken to a SharedPreference storage. Because it's not a good idea to save it in a database. If your application doesn't need to use a database then it has no reason to create a database just to store one value. Use that saved access token to verify the session and it will work for you.
May this will help you... cheers...

Implement Single Sign on in for Android Applications

I have 4-5 Android applications and I want to implement Single Sign on for all these apps. So that if user has logged into any one of that apps he won't be asked to log in again for other applications. How can I accomplish it in Android??
Implementing a SSO requires having a common database holding the user credential information. One way of doing it is implementing your own authentication server which exposes a login, register, reset and forgot password APIs which each of your apps would use to login into the application.
Lets say you are using JWT to maintain statelessness, which means auth server responds with a JWT for every successful login through any android app.
So your launcher activity in each of your app should not be login but the dashboard or whatever the user sees after login. In the on_create of the dashboard, check if there is an existing jwt available in the shared preferences. If there is one, go ahead with the dashboard. But if there isnt one, goto login activity and let the user login first. Once logged in, preserve the jwt in shared preferences for the other apps to use it. You need to make sure that all the shared preferences are using the same namespace to access the jwt.
To make it more effective, you can implement a library module for login, regd and forgot password to be included into each app and you would have that part for all the apps ready. The XML files for three activities can be included into the lib itself and app will load them from the lib file if it doesnt find it in the app drawables.
Now coming to server part, implementing your custom auth server, say using OAuth2 is one way but to make it easier, there are 3rd party solutions like Stormpath or CAS which would provide such a service. May be you can find one which is free too.
Instead of JWT, you could use userId (primary key in the user database) to identify if the user is logged in or not.
Another point to consider is if the application server for each of these apps, if they have one, are using JWT or userId to respond to app requests and based on that auth server communication token should be decided. Needless to say, that application server and the auth server should also communicate among them to sync user information for app. This would be the same even if you are using a 3rd party auth server which would talk to a single database holding the entire user information but you might need to work on syncing your application server with 3rd party auth server
However, the tricky part is in logout and reset password and change password. I am not talking about the logout process if JWT is used, which has its own challenges to meet, but I am talking about the logout when SSO is used. If the user logs out from one of the apps you need to decide if the user has to be logged out from the rest of the apps or not. Both can be handled though but usually it would be a single sign out for ease of implementation and it would provide a good UX too.
Also, if any of these apps has a website version and the user changes or resets password from the website, you need to make sure that user logs in again on the device when he first uses the app after the change. However this logic has to be managed entirely on the server side inside the auth server.
Though your question is related to android app only, you might have to implement a server for that and modify the appl server too for each of the app. There might be a chance that this might not be your question essence entirely, but your actual requirement might help me to help you implement this.

Categories

Resources