DEV Community 👩‍💻👨‍💻

Cover image for Anonymous Auth with Firebase on Android
victor
victor

Posted on

Anonymous Auth with Firebase on Android

When working with firebase Authentication, temporary anonymous accounts can be created to authenticate with Firebase for a user not signed up to your app to store and work with data protected by security rules. In the event that the anonymous user decides to sign up to your app, you can interface their sign-in accreditations so they can keep on working with their ensured information in future sessions.

installation

  • Add Firebase to your android project If you haven't already
  • Add the dependency for the Firebase Authentication Android library to your module (app-level) Gradle file (usually app/build.gradle):
implementation 'com.google.firebase:firebase-auth:18.1.0'
Enter fullscreen mode Exit fullscreen mode
  • connect your app to your Firebase project, do so from the Firebase console.
  • Enable anonymous auth: In the Firebase console, open the Auth section. On the Sign-in Methods page, enable the >Anonymous sign-in method.

Usage

  • In your activity's onCreate method, get the shared instance of the FirebaseAuth object:
private FirebaseAuth mAuth;
// ...
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance(); 
Enter fullscreen mode Exit fullscreen mode
  • When initializing your Activity, check to see if the user is currently signed in:
@Override
public void onStart() {
    super.onStart();
    // Check if user is signed in (non-null) and update UI accordingly.
    FirebaseUser currentUser = mAuth.getCurrentUser();
    updateUI(currentUser);
} 
Enter fullscreen mode Exit fullscreen mode
  • call signInAnonymously to sign in as an anonymous user:
mAuth.signInAnonymously()
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    // Sign in success, update UI with the signed-in users information
                    Log.d(TAG, "signInAnonymously:success");
                    FirebaseUser user = mAuth.getCurrentUser();
                    updateUI(user);
                } else {
                    // If sign in fails, display a message to the user.
                    Log.w(TAG, "signInAnonymously:failure", task.getException());
                    Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.",
                            Toast.LENGTH_SHORT).show();
                    updateUI(null);
                }

                // ...
            }
        }); 
Enter fullscreen mode Exit fullscreen mode

use getCurrentUser method to get account data for the signed in user

migrate an anonymous account to a permanent account

  • When the user signs up, complete the sign-in flow for the user's authentication provider up to, but not including, calling one of the FirebaseAuth.signInWith methods.

  • Get an AuthCredential for the new authentication provider:
    Email and password

AuthCredential credential = EmailAuthProvider.getCredential(email, password);
Enter fullscreen mode Exit fullscreen mode
  • Pass the AuthCredential object to the sign-in user's linkWithCredential method
mAuth.getCurrentUser().linkWithCredential(credential)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "linkWithCredential:success");
                    FirebaseUser user = task.getResult().getUser();
                    updateUI(user);
                } else {
                    Log.w(TAG, "linkWithCredential:failure", task.getException());
                    Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.",
                            Toast.LENGTH_SHORT).show();
                    updateUI(null);
                }

                // ...
            }
        });
Enter fullscreen mode Exit fullscreen mode

if linkWithCredential method call was successfull, the anonymous account data will be maigrated to the new user

Top comments (0)

🌚 Life is too short to browse without dark mode