Anonymous Auth with Firebase on Android
Tags: firebase, auth, guid, anonymous
Published: 2019-08-14 10:04:10

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](https://firebase.google.com/docs/android/setup) 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*):
```bash
implementation 'com.google.firebase:firebase-auth:18.1.0'
```
- connect your app to your Firebase project, do so from the [Firebase console.](https://console.firebase.google.com/)
- Enable anonymous auth: In the [Firebase console](https://console.firebase.google.com/), 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: 
```bash
private FirebaseAuth mAuth;
// ...
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance(); 
```
- When initializing your Activity, check to see if the user is currently signed in:
```bash 
@Override
public void onStart() {
    super.onStart();
    // Check if user is signed in (non-null) and update UI accordingly.
    FirebaseUser currentUser = mAuth.getCurrentUser();
    updateUI(currentUser);
} 
```
- call *signInAnonymously* to sign in as an anonymous user: 
```bash
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);
                }

                // ...
            }
        }); 
```
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**
```bash
AuthCredential credential = EmailAuthProvider.getCredential(email, password);
```
- Pass the *AuthCredential* object to the sign-in user's *linkWithCredential* method
```bash
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);
                }

                // ...
            }
        });
```
if *linkWithCredential* method call was successfull, the anonymous account data will be maigrated to the new user