27

I'm developing a small android app, and basically so far it just has login and logout functionality. I'm using Firebase to store user data and also for authentication.

So I have login working and it authenticates users as it should and I have logging out working in the sense that it unauthenticates users. But is there anything I have to do from within the app to kill the session?

if (id == R.id.action_log_out) {
    ref.unauth(); //End user session
    startActivity(new Intent(MainActivity.this, LoginActivity.class)); //Go back to home page
    finish();
}        

Will this work as I think it should? Obviously if someone logs out they shouldn't be able to hit th back button and magically go back to the last page without re-logging in.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
John
  • 1,808
  • 7
  • 28
  • 57
  • Hey, what is the type of ref in your code? – karan vs Sep 14 '16 at 09:26
  • It's `Firebase`, https://firebase.google.com. They make it pretty easy for setting up a quick database and authentication, etc. – John Sep 14 '16 at 12:18
  • 1
    Actually I was using FireBaseAuth to authenticate users in android and was finding a way to end user session. Seems they already have a method for this, call signOut() on FireBaseAuth object. Anyway, thanks for your explaination. – karan vs Sep 15 '16 at 05:23
  • 1
    Well this question is a few months old, but I think that `.signOut()` has taken the place of `unauth()`. Everything I see with `unauth()` now is deprecated it seems. :) – John Sep 15 '16 at 13:33

6 Answers6

40

From Firebase docs

https://firebase.google.com/docs/auth/android/custom-auth

call this FirebaseAuth.getInstance().signOut();

Manzurul Hoque Rumi
  • 2,911
  • 4
  • 20
  • 43
  • I used this and it is working fine except samsung devices. I am checking Auth variable to null , if so then i am redirecting user to the app but in samsung devices condition auth!=null gets satisfied even user is logged out . – xaif Sep 08 '19 at 04:27
13

When Firebase authenticates the user (or you authenticate the user with Firebase), it stores the token for that user in local storage on your device. This happens when you call one of the authWith... methods (of course only if it successfully authenticates the user).

Calling ref.unauth(); immediately deletes that token from local storage.

A properly implemented flow would not automatically re-authenticate them when the user presses the back button, but that depends on the flow you implement (which is missing from your question and would likely be too much code anyway).

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Ok got it ! Thanks for the clarification – John Feb 21 '16 at 21:29
  • 1
    I used `AuthUI.getInstance() .createSignInIntentBuilder()` for signing in to my app using Google, Email accounts. In this case, what logic would work ? I've seen your answer above. Here `ref` represents what ? Can you please solve my problem. Please see this [post](http://stackoverflow.com/questions/43959857/not-able-to-get-the-array-values-from-firebase-database) – coderpc May 14 '17 at 17:17
  • 1
    Same doubt here, I use `signInWithCredential` so what is `ref`? – cutiko Nov 14 '17 at 17:45
  • 6
    This answer is based on Firebase 2.x, from before May 2016. In later versions the equivalent is `FirebaseAuth.getInstance().signOut();` – Frank van Puffelen Nov 14 '17 at 18:01
  • @FrankvanPuffelen thanks for being available, it took me a while to realize the API changed, had to check the git history https://github.com/firebase/quickstart-android/commit/141d34bae9e74e5e67eea72ba07327e49036c5bb#diff-e86aec0969888fd8d9edd50c98a2e341 I will try to see what I can do – cutiko Nov 14 '17 at 18:17
  • If any one else is having this same problem related with Google login here is my answer https://stackoverflow.com/questions/38707133/google-firebase-sign-out-and-forget-user-in-android-app/47293185#47293185 – cutiko Nov 14 '17 at 18:49
  • @FrankvanPuffelen should we sign out manually or Firebase automatically sign out before when we call `signInWithEmailAndPassword` method again? – ysfcyln Apr 21 '19 at 16:58
  • There can be only one signed in user in a `FirebaseApp` instance. So if you sign in a different user, the previous user is signed out. There is no different in whether that happens implicitly or explicitly. – Frank van Puffelen Apr 21 '19 at 17:00
  • ref is unresolved reference in my case. What is ref for? – Liker777 Mar 04 '21 at 05:53
6

I see 2 options for the issue we have with the back-Button after Logout:

In your LoginActivity, wich should be you launcher activity, Override onBackPressed Method and leave it empty:

    @Override
public void onBackPressed() {
// empty so nothing happens
}

Or/and you can add the LoginActivityIntent in your LogoutActivty if user == null. This way, whenever a not authenticated user lands on the activity, it will redirect to the LoginActivity instantly, although this looks kinda weird.

        mAuth = FirebaseAuth.getInstance();
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG,"onAuthStateChanged:signed_out");
                startActivity(new Intent(LogoutActivity.this, LoginActivity.class));
            }
            // ...
        }
    };

First Option is easier, but I guess if you apply both your on the save side ^^ Im coding for 2 weeks now so correct me if im wrong.

Daniel Eberl
  • 1,268
  • 1
  • 10
  • 22
3

You can replace finish() with finishAffinity();

0

Delete tokens and Instance IDs

String authorizedEntity = PROJECT_ID;  
String scope = "GCM";
FirebaseInstanceID.getInstance(context).deleteToken(authorizedEntity,scope);

You can also delete the Instance ID itself, including all associated tokens. The next time you call getInstance() you will get a new Instance ID:

FirebaseInstanceID.getInstance(context).deleteInstanceID();
String newIID = InstanceID.getInstance(context).getId();
Ebin Joy
  • 2,690
  • 5
  • 26
  • 39
-1
private void sendToLogin() { //funtion
    GoogleSignInClient mGoogleSignInClient ;
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestIdToken(getString(R.string.default_web_client_id))
        .requestEmail()
        .build();
    mGoogleSignInClient = GoogleSignIn.getClient(getBaseContext(), gso);
    mGoogleSignInClient.signOut().addOnCompleteListener(/*CURRENT CLASS */.this,
        new OnCompleteListener<Void>() {  //signout Google
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                FirebaseAuth.getInstance().signOut(); //signout firebase
                Intent setupIntent = new Intent(getBaseContext(), /*To ur activity calss*/);
                Toast.makeText(getBaseContext(), "Logged Out", Toast.LENGTH_LONG).show(); //if u want to show some text
                setupIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(setupIntent);
                finish();
            }
        });
}

this code is written to work as copy past just read COMMENTS in code to customize it to ur needs, i prefer to send user to login

Sumer Singh
  • 468
  • 4
  • 9