0
0

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-27

Authenticate Using Google Sign-In on Android を翻訳してみました。
お気づきの点があればコメント頂ければと思います。

以下、関連する投稿へのリンクです。
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 Using Google Sign-In on Android

You can let your users authenticate with Firebase using their Google Accounts by integrating Google Sign-In into your app.

あなたは、あなたのアプリにGoogleサインインを統合することで、ユーザーに彼らのGoogleアカウントを使用してFirebaseで認証させることが出来ます。

Before you begin

1.Add Firebase to your Android project.
2.Add the dependencies for Firebase Authentication and Google Sign-In to your app-level build.gradle file:

compile 'com.google.firebase:firebase-auth:9.4.0'
compile 'com.google.android.gms:play-services-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 Google Sign-In in the Firebase console:
  a.In the Firebase console, open the Auth section.
  b.On the Sign in method tab, enable the Google sign-in method and click Save.

Google Sign-In requires an SHA1 fingerprint: see Authenticating Your Client for details.

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

compile 'com.google.firebase:firebase-auth:9.4.0'
compile 'com.google.android.gms:play-services-auth:9.4.0'

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

  a.FirebaseコンソールAuthセクションを開きます。
  b.サインイン方法のタブで、Googleサインインを有効にして保存をクリックします。

GoogleサインインはSHA1フィンガープリントを必要とします:詳しくはAuthenticating Your Clientを参照してください。

Authenticate with Firebase

1.Integrate Google Sign-In into your app by following the steps on the Integrating Google Sign-In into Your Android App page. When you configure the GoogleSignInOptions object, call requestIdToken:

            // Configure Google Sign In
            GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestIdToken(getString(R.string.default_web_client_id))
                    .requestEmail()
                    .build();

GoogleSignInActivity.java

You must pass your server's client ID to the requestIdToken method. To find the OAuth 2.0 client ID:

  a.Open the Credentials page in the API Console.
  b.The Web application type client ID is your backend server's OAuth 2.0 client ID.

After you integrate Google Sign-In, your sign-in activity has code similar to the following:

        private void signIn() {
            Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
            startActivityForResult(signInIntent, RC_SIGN_IN);
        }
>
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
>
            // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
            if (requestCode == RC_SIGN_IN) {
                GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                if (result.isSuccess()) {
                    // Google Sign In was successful, authenticate with Firebase
                    GoogleSignInAccount account = result.getSignInAccount();
                    firebaseAuthWithGoogle(account);
                } else {
                    // Google Sign In failed, update UI appropriately
                    // ...
                }
            }
        }

GoogleSignInActivity.java

2.In your sign-in activity's onCreate method, get the shared instance of the FirebaseAuth object:

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

GoogleSignInActivity.java

3.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);
            }
        }

GoogleSignInActivity.java

4.After a user successfully signs in, get an ID token from the GoogleSignInAccount object, exchange it for a Firebase credential, and authenticate with Firebase using the Firebase credential:

        private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
            Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
>
            AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
            mAuth.signInWithCredential(credential)
                    .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            Log.d(TAG, "signInWithCredential: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, "signInWithCredential", task.getException());
                                Toast.makeText(GoogleSignInActivity.this, "Authentication failed.",
                                        Toast.LENGTH_SHORT).show();
                            }
                            // ...
                        }
                    });
        }

GoogleSignInActivity.java

If the call to signInWithCredential succeeds, the AuthStateListener runs the onAuthStateChanged callback. In the callback, you can use the getCurrentUser method to get the user's account data.

1.あなたのAndroidアプリへのGoogleサインインの統合ページの次の手順であなたのアプリにGoogleサインインを統合します。 GoogleSignInOptionsオブジェクトの設定を行うときは、requestIdTokenを呼び出します:

            // Configure Google Sign In
            GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestIdToken(getString(R.string.default_web_client_id))
                    .requestEmail()
                    .build();

GoogleSignInActivity.java

あなたはrequestIdTokenメソッドにあなたのサーバーのクライアントIDを渡す必要があります。 OAuth 2.0 クライアントIDを見つけるには:

  a.APIコンソールの証明ページを開く
  b.ウェブアプリケーションタイプクライアントIDはあなたのバックエンドサーバーのOAuth 2.0クライアントIDです

Googleサインインを統合すると、あなたのサインインactivityは次のようになります:

        private void signIn() {
            Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
            startActivityForResult(signInIntent, RC_SIGN_IN);
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
            if (requestCode == RC_SIGN_IN) {
                GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                if (result.isSuccess()) {
                    // Google Sign In was successful, authenticate with Firebase
                    GoogleSignInAccount account = result.getSignInAccount();
                    firebaseAuthWithGoogle(account);
                } else {
                    // Google Sign In failed, update UI appropriately
                    // ...
                }
            }
        }

GoogleSignInActivity.java

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

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

GoogleSignInActivity.java

3.ユーザーのサインイン状態の変更に応じる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);
            }
        }

GoogleSignInActivity.java

4.ユーザーがサインインに成功したら、GoogleSignInAccountオブジェクトからIDトークンを取得し、それをFirebase証明に変換し、Firebase証明を使用してFirebaseで認証します:

        private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
            Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

            AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
            mAuth.signInWithCredential(credential)
                    .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            Log.d(TAG, "signInWithCredential: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, "signInWithCredential", task.getException());
                                Toast.makeText(GoogleSignInActivity.this, "Authentication failed.",
                                        Toast.LENGTH_SHORT).show();
                            }
                            // ...
                        }
                    });
        }

GoogleSignInActivity.java

signInWithCredentialの呼出が成功すると、AuthStateListeneronAuthStateChangedコールバックが呼ばれます。 コールバックで、あなたはユーザーのアカウントデータを取得するためにgetCurrentUserメソッドを使用できます。

Next steps

After a user signs in for the first time, a new user account is created and linked to the credentials—that is, the user name and password, or auth provider information—the user signed in with. This new account is stored as part of your Firebase project, and can be used to identify a user across every app in your project, regardless of how the user signs in.



  • In your Firebase Realtime Database and Firebase Storage Security Rules, you can get the signed-in user's unique user ID from the auth variable, and use it to control what data a user can access.

You can allow users to sign in to your app using multiple authentication providers by linking auth provider credentials to an existing user account.

To sign out a user, call signOut:

FirebaseAuth.getInstance().signOut();

初めてユーザーがサインインした後、新しいユーザーアカウントが作成され、そしてユーザーがサインインに使用した証明(ユーザー名とパスワード、または認証プロバイダの情報)にリンクされます。 この新しいアカウントはあなたのFirebaseプロジェクトの一部として保存され、ユーザーがどのようにサインインするかにかかわらず、あなたのプロジェクト内のすべてのアプリでユーザーの識別に使用できます。

  • あなたのアプリにて、あなたはFirebaseUserオブジェクトからユーザーの基本的なプロフィール情報を取得できます。 Manage Usersを参照してください。


  • あなたのFirebase Realtime DatabaseとFirebase Storageのセキュリティルールにて、あなたはauth変数からサインインしたユーザーのユニークユーザーIDを取得できます。 そしてそれをユーザーがどのデータにアクセス出来るかをコントロールするために使用できます。

あなたは既存のユーザーアカウントに認証プロバイダの証明をリンクすることで、ユーザーが複数の認証プロバイダーであなたのアプリにサインインすることを可能に出来ます。

ユーザーをサインアウトさせるには、signOutを呼んでください:

FirebaseAuth.getInstance().signOut();
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?