4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[翻訳] Firebase Authentication / Android / Anonymous Authentication

Last updated at Posted at 2016-08-31

Anonymous Authentication を翻訳してみました。
お気づきの点があればコメント頂ければと思います。

以下、関連する投稿へのリンクです。
Firebase Authentication / Introduction
Firebase Authentication / Users in Firebase Projects
Firebase Authentication / Android / Manage Users
Firebase Authentication / Android / Password Authentication
Firebase Authentication / Android / Google Sign-In
Firebase Authentication / Android / Anonymous Authentication

Authenticate with Firebase Anonymously on Android

You can use Firebase Authentication to create and use temporary anonymous accounts to authenticate with Firebase. These temporary anonymous accounts can be used to allow users who haven't yet signed up to your app to to work with data protected by security rules. If an anonymous user decides to sign up to your app, you can link their sign-in credentials to the anonymous account so that they can continue to work with their protected data in future sessions.

あなたはFirebaseで認証するための一時的な匿名アカウントを作成し、使用するためにFirebase Authenticationを利用できます。 これらの一時的な匿名アカウントは、まだあなたのアプリにサインアップしていないユーザーにセキュリティルールで保護されたデータで作業させることを可能にするために使用できます。 もし匿名ユーザーがあなたのアプリにサインアップすることを決めた場合、かれらが今後のセッションで保護されたデータで作業を続けられるようにするため、あなたはかれらの証明を匿名アカウントにリンクできます。

Before you begin

1.Add Firebase to your Android project.
2.Add the dependency for Firebase Authentication to your app-level build.gradle file:

    compile 'com.google.firebase:firebase-auth:9.4.0'

3.If you haven't yet connected your app to your Firebase project, do so from the Firebase console.
4.Enable anonymous auth:
  a.In the Firebase console, open the Auth section.
  b.On the Sign-in Methods page, enable the Anonymous sign-in method.

1.あなたのAndroidプロジェクトにFirebaseを追加
2.あなたのアプリレベルのbuild.gradleにFirebase Authenticationへの依存を追加

compile 'com.google.firebase:firebase-auth:9.4.0'

3.もしまだあなたのアプリをFirebaseプロジェクトに連携させていないならば、Firebaseコンソールでそれを行います。
4.匿名認証を有効にします。

  a.FirebaseコンソールAuthセクションを開きます。
  b.サインイン方法のタブで、匿名認証を有効にします。

Authenticate with Firebase anonymously

When a signed-out user uses an app feature that requires authentication with Firebase, sign in the user anonymously by completing the following steps:

1.In your activity's onCreate method, get the shared instance of the FirebaseAuth object:

    private FirebaseAuth mAuth;
    // ...
    mAuth = FirebaseAuth.getInstance();

AnonymousAuthActivity.java

2.Set up an AuthStateListener that responds to changes in the user's sign-in state:

    private FirebaseAuth.AuthStateListener mAuthListener;
>
    // ...
>
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // ...
        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");
                }
                // ...
            }
        };
        // ...
    }
>
    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }
>
    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

AnonymousAuthActivity.java

3.Finally, call signInAnonymously to sign in as an anonymous user:

    mAuth.signInAnonymously()
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d(TAG, "signInAnonymously:onComplete:" + task.isSuccessful());
>
                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        Log.w(TAG, "signInAnonymously", task.getException());
                        Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }
>
                    // ...
                }
            });

AnonymousAuthActivity.java

If sign-in succeeds, the AuthStateListener runs the onAuthStateChanged callback, in which you can use the getCurrentUser method to get the user's account data.

サインアウトしたユーザーがFirebaseの認証を必要とするアプリの機能を使用するとき、次の手順でユーザーを匿名サインインさせます:

1.あなたのactivityのonCreateメソッドで、FirebaseAuthオブジェクトの共有インスタンスを取得します:

    private FirebaseAuth mAuth;
    // ...
    mAuth = FirebaseAuth.getInstance();

AnonymousAuthActivity.java

2.ユーザーのサインイン状態の変更に対応するため、AuthStateListenerをセットアップします:

    private FirebaseAuth.AuthStateListener mAuthListener;

    // ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // ...
        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");
                }
                // ...
            }
        };
        // ...
    }

    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

AnonymousAuthActivity.java

3.最後に、匿名ユーザーとしてサインインするためにsignInAnonymouslyを呼び出します:

    mAuth.signInAnonymously()
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d(TAG, "signInAnonymously:onComplete:" + task.isSuccessful());

                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        Log.w(TAG, "signInAnonymously", task.getException());
                        Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }

                    // ...
                }
            });

AnonymousAuthActivity.java

サインインが成功すると、あなたがユーザーアカウントデータを取得するためにgetCurrentUserメソッドを呼び出せるAuthStateListeneronAuthStateChangedコールバックが呼ばれます。

Convert an anonymous account to a permanent account

When an anonymous user signs up to your app, you might want to allow them to continue their work with their new account—for example, you might want to make the items the user added to their shopping cart before they signed up available in their new account's shopping cart. To do so, complete the following steps:

1.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. For example, get the user's Google ID token, Facebook access token, or email address and password.

2.Get an AuthCredential for the new authentication provider:

Google Sign-In

    AuthCredential credential = GoogleAuthProvider.getCredential(googleIdToken, null);

Facebook Login

    AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());

Email-password sign-in

AuthCredential credential = EmailAuthProvider.getEmailAuthCredential(email, password);

3.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) {
                    Log.d(TAG, "linkWithCredential:onComplete:" + task.isSuccessful());
>
                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }
>
                    // ...
                }
            });

AnonymousAuthActivity.java

If the call to linkWithCredential succeeds, the user's new account can access the anonymous account's Firebase data.

This technique can also be used to link any two accounts.

匿名ユーザーがあなたのアプリにサインアップしたとき、あなたは彼らが新しいアカウントで処理を続行することを可能にさせたい思うかもしれない。 (例えば、あなたはユーザーがサインアップ前にショッピングカートに追加したアイテムを、彼らの新しいアカウントのショッピングカートで利用できるようにしたいと思うかもしれない。) これを行うには、次の手順を実行します:

1.ユーザーがサインアップし、ユーザーの認証プロバイダへのサインインフローを完了し、しかしまだ(ユーザーのGoogle IDトークンFacebookアクセストークン、またはメールアドレスとパスワードなどの)FirebaseAuth.signInWithメソッドのいずれも呼び出されていないとき。

2.新しい認証プロバイダのAuthCredentialを取得します:

Google Sign-In

    AuthCredential credential = GoogleAuthProvider.getCredential(googleIdToken, null);

Facebook Login

    AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());

Email-password sign-in

AuthCredential credential = EmailAuthProvider.getEmailAuthCredential(email, password);

3.サインインユーザーのlinkWithCredentialメソッドにAuthCredentialオブジェクトを渡します:

    mAuth.getCurrentUser().linkWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d(TAG, "linkWithCredential:onComplete:" + task.isSuccessful());

                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }

                    // ...
                }
            });

AnonymousAuthActivity.java

linkWithCredentialの呼出が成功すると、ユーザーの新しいアカウントは匿名アカウントのFirebaseデータにアクセスできるようになります。

またこのテクニックは、任意の二つのアカウントをリンクするためにも使えます。

Next steps

Now that users can authenticate with Firebase, you can control their access to data in your Firebase database using Firebase rules.

これまでの通りでユーザーはFirebaseで認証できます。 あなたはFirebaseルールでFirebaseデータベース内のデータへの彼らのアクセスをコントロールできます。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?