简体   繁体   中英

Firebase: How to keep an Android user logged in?

I'm using Firebase SimpleLogin to enable Email / Password authentication. Creation of users and subsequent login is all working fine. However, whenever I leave the app (even if only for a few seconds) the user is never logged in on my return ie..

authClient.checkAuthStatus(new SimpleLoginAuthenticatedHandler())...

Always returns a null user.

I am not logging out the user via the API. Also I have set the number of days the user is logged in to 21 in the Firebase console.

I have seen mention of a remember-me param in the JS docs, but I can't see any equivalent for Android / Java.

Wondering if I'm missing anything in the docs or if it's not possible for Android?

Thanks for your help,

Neil.

Edit: Added code sample.

User creation....

public void registerUserForChat(final MyApplication application, String email, String password) {
    Firebase ref = new Firebase(FIREBASE_URL);
    SimpleLogin authClient = new SimpleLogin(ref);
    authClient.createUser(email, password, new SimpleLoginAuthenticatedHandler() {
        @Override
        public void authenticated(com.firebase.simplelogin.enums.Error error, User user) {
            if(error != null) {
                Log.e(TAG, "Error attempting to create new Firebase User: " + error);
            }
            else {
                Log.d(TAG, "User successfully registered for Firebase");
                application.setLoggedIntoChat(true);
            }
        }
    });
}

User login....

public void loginUserForChat(final MyApplication application,  String email, String password) {
    Log.d(TAG, "Attempting to login Firebase user...");
    Firebase ref = new Firebase(FirebaseService.FIREBASE_URL);
    final SimpleLogin authClient = new SimpleLogin(ref);
    authClient.checkAuthStatus(new SimpleLoginAuthenticatedHandler() {
        @Override
        public void authenticated(com.firebase.simplelogin.enums.Error error, User user) {
            if (error != null) {
                Log.d(TAG, "error performing check: " + error);
            } else if (user == null) {
                Log.d(TAG, "no user logged in. Will login...");
                authClient.loginWithEmail(email, password, new SimpleLoginAuthenticatedHandler() {
                    @Override
                    public void authenticated(com.firebase.simplelogin.enums.Error error, User user) {
                        if(error != null) {
                            if(com.firebase.simplelogin.enums.Error.UserDoesNotExist == error) {
                                Log.e(TAG, "UserDoesNotExist!");
                            } else {
                                Log.e(TAG, "Error attempting to login Firebase User: " + error);
                            }
                        }
                        else {
                            Log.d(TAG, "User successfully logged into Firebase");
                            application.setLoggedIntoChat(true);
                        }
                    }
                });
            } else {
                Log.d(TAG, "user is logged in");
            }
        }
    });
}

So loginUserForChat method first checks to see if there is a logged in user and, if not, performs the login. Note that every time I start the app, the logging I see is....

  1. Attempting to login Firebase user...
  2. no user logged in. Will login...
  3. User successfully logged into Firebase

If I exit the app, even for a few seconds, and return - I see the same logging.

One thing I noticed is that the call to checkAuthStatus does not take any user credentials - I assume it just checks for any locally logged in user?

Much appreciated.

[Engineer at Firebase] In order to transparently handle persistent sessions in the Firebase Simple Login Java client, you need to use the two-argument constructor which accepts an Android context, ie SimpleLogin(com.firebase.client.Firebase ref, android.content.Context context) every time you instantiate the Simple Login Java client.

See https://www.firebase.com/docs/java-simple-login-api/javadoc/com/firebase/simplelogin/SimpleLogin.html for the full API reference.

Another way - try this code in your onCreate :

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    // User is signed in
    Intent i = new Intent(LoginActivity.this, MainActivity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(i);
} else {
    // User is signed out
    Log.d(TAG, "onAuthStateChanged:signed_out");
}

This will keep the user logged in by taking the user to the Main activity directly without stopping at registration activity. so the user will be logged in unless the user click on signout.

The proper way to do it is to use oAuth authentication:

1. The user logs in.
2. You generate an access token(oAuth2).
3. Android app saves the token locally.
4. Each time the comes back to the auth, he can use the token to to log in, unless the token has been revoked by you, or he changed his
password.

Luckily, firebase has an out of the box support for that, docs:

https://www.firebase.com/docs/security/custom-login.html https://www.firebase.com/docs/security/authentication.html

You can do this by Using this Approach to escape logi page if User already logged in.

private FirebaseAuth auth;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    auth = FirebaseAuth.getInstance();

    if (auth.getCurrentUser() != null) {
        startActivity(new Intent(Login_Activity.this, Home.class));
        finish();
    }
    setContentView(R.layout.activity_login_);

for those using Kotlin, to keep the user logged in just add in the onCreate function

if (auth.currentUser != null) 
{
startActivity(Intent(this@Login, SellingPageHolderActivity::class.java))
finish()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM