Facebook Session Destroyed after application closed - android

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...

Related

what is the best way to implement one-time login feature

I would like my app has the following feature:
User login with username and passowrd when first time install the app on phone. After successfully logged in, everytime when user launch the app again, the app doesn't ask for login credential again, but directly shows the landing screen. (Of course if user clear app data, the app will ask for login again)
The way to implement the feature in my mind could be that the app stores username and password in SharedPreferences once user login successfully, then, when user launch the app again, my code could check if there are username and password in ShareadPrefereces, if so, directly show the landing page.
My question:
I am not sure whether it is safe or really a good practice to store user's login credential in SharedPreferences? If not, what is the best way to implement this one-time login feature?
(I am doing it for both Android and iOS. So, I would like to hear both Android good solution and iOS solution. Thanks!)
It's a bad practice to store credentials in SharedPreferences. In fact it's bad to store credentials anywhere on user's device.
Using some encrypting library, for example Hawk for android would be a better, but still not recommended option.
Better way would require some work on the backend side: in return to user's credentials server would return a token which can be used leter for authorization. The token would expire in some fixed amount of time (like day, week, etc.). Before this time passes you can make another request and update your token for a new one which will live another week (day, month etc.)
Even better approach would be to save the token using Hawk (or some other similar lib)

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.

User Session Management in android

I want to maintain user session once the user logs into his/her account so that they are logged in even after the application is closed and started again. Searching on Google and SO, people referred SharedPreferences. I understand that I have to store user details in SP(SharedPreferences), but what if the user updates his/her data? Plus, the HttpGet call I send to the link to get user data returns the valid data(JSON) only when the user is logged in. Is SP the only way to do this, or is there other and more efficient way to do this?
P.S. - I am working as a freelance for a startup, and they have API to their PHP website. I have to make an android app for their website. To log in the user to the website, I make a Http POST call to their API and the result I get is a JSON. If the JSON contains "success" value to the "result" key, then the user is logged in. But as soon as I use intent to go to the next activity(where I have to display the user data by making Http Get call to another API, which only works if the user is logged in), the session is lost. Since I work as a freelance, they don't really trust me giving cookies to user sessions. So, I was hoping there might me some other way?
You can always use cookies (with, say, an authentication token?), Android OS manages them for your app automatically - as long as the cookie is correctly set by the server (ex. expiration date) your app should work fine. But this is a little old school.
A more modern way is to use OAuth or integrate an already existing login system (Facebook, Google, etc.) to authenticate users.
Using Shared Preferences is a wrong tool for this job. It's a workaround for doing proper authentication. There are ways that are trustworthy and secure and take care of all kinds of edge cases, and while it takes a little bit of work to set up, it's a much better option, IMO.
You should try to integrate android AccountManger APIs because storing the credentials in shared preferences is not especially desirable from security point,especially if your app is going to run on rooted devices.
From the docs:
public class AccountManager extends Object java.lang.Object ↳
android.accounts.AccountManager Class Overview
This class provides access to a centralized registry of the user's
online accounts. The user enters credentials (username and password)
once per account, granting applications access to online resources
with "one-click" approval.
Different online services have different ways of handling accounts and
authentication, so the account manager uses pluggable authenticator
modules for different account types. Authenticators (which may be
written by third parties) handle the actual details of validating
account credentials and storing account information. For example,
Google, Facebook, and Microsoft Exchange each have their own
authenticator.
Many servers support some notion of an authentication token, which can
be used to authenticate a request to the server without sending the
user's actual password. (Auth tokens are normally created with a
separate request which does include the user's credentials.)
AccountManager can generate auth tokens for applications, so the
application doesn't need to handle passwords directly. Auth tokens are
normally reusable and cached by AccountManager, but must be refreshed
periodically. It's the responsibility of applications to invalidate
auth tokens when they stop working so the AccountManager knows it
needs to regenerate them.
\

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.

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

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

Categories

Resources