web-dev-qa-db-fra.com

Firebase et le nouveau Google Sign-In sur Android

J'essaie d'ajouter un support pour le nouveau compte Google Sign-in annoncé dans le cadre de Play services 8.3.0. J'ai configuré le projet avec succès et j'obtiens un jeton de GoogleApiClient, mais Firebase renvoie un fichier Invalid Credentials error lorsque vous appelez ref.authWithOAuthToken("google", token)

La connexion Google+ fonctionne, mais cela nécessite une autorisation distincte, ce qui est pénible lors du développement pour Marshmallow . Didacticiel Firebase Android possède un exemple de connexion Google+ et j’ai le sentiment qu’ils n’ont pas de soutien pour nouvelle connexion Google pour le moment. 

Quelqu'un a-t-il essayé le nouveau compte Google Sign-In en relation avec Firebase et l'a fait fonctionner?

16
Bogdan M.

C'est un mélange des étapes de Ajouter une connexion à Android et Autoriser avec Google les API REST .

Une fois que vous avez une GoogleSignInResult, vous pouvez obtenir le nom du compte puis demander le jeton avec les portées minimales:

@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);
        GoogleSignInAccount acct = result.getSignInAccount();

        String email = acct.getEmail();

        // TODO: run an async task to get an OAuth2 token for the account
    }
}

La tâche asynchrone devra demander ces étendues:

protected String doInBackground(String... params) {
    String scopes = "oauth2:profile email";
    String token = GoogleAuthUtil.getToken(getApplicationContext(), email, scopes);
    // exception handling removed for brevity
    return token;
}

Vous pouvez maintenant utiliser le jeton pour vous connecter à Firebase comme d'habitude:

ref.authWithOAuthToken("google", token, new Firebase.AuthResultHandler() {...
28
Frank van Puffelen

Téléchargez le code source à partir d’ici ( Firebase Google Login Android ). Dans ce blog, j'ai également fourni la capture d'écran pour vous aider.

activity_main.xml

<RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    Android:orientation="vertical">


    <LinearLayout
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:layout_centerInParent="true"
        Android:orientation="vertical">


        <ImageView
            Android:layout_width="150dp"
            Android:id="@+id/iv_image"
            Android:src="@drawable/profileimage"
            Android:layout_gravity="center"
            Android:layout_height="150dp" />

        <LinearLayout
            Android:layout_width="match_parent"
            Android:layout_marginTop="5dp"
            Android:layout_height="40dp">

            <TextView
                Android:layout_width="100dp"
                Android:layout_height="wrap_content"
                Android:layout_gravity="center_vertical"
                Android:layout_marginLeft="10dp"
                Android:text="Name"
                Android:textColor="#000000"
                Android:textSize="15dp" />


            <TextView
                Android:layout_width="wrap_content"
                Android:layout_height="wrap_content"
                Android:layout_gravity="center_vertical"
                Android:layout_marginLeft="10dp"
                Android:text="Name"
                Android:id="@+id/tv_name"
                Android:textColor="#000000"
                Android:textSize="15dp" />

        </LinearLayout>

        <View
            Android:layout_width="match_parent"
            Android:layout_height="1dp"
            Android:background="#000000"></View>


        <LinearLayout
            Android:layout_width="match_parent"
            Android:layout_height="40dp">

            <TextView
                Android:layout_width="100dp"
                Android:layout_height="wrap_content"
                Android:layout_gravity="center_vertical"
                Android:layout_marginLeft="10dp"
                Android:text="Email"
                Android:textColor="#000000"
                Android:textSize="15dp" />


            <TextView
                Android:layout_width="wrap_content"
                Android:layout_height="wrap_content"
                Android:layout_gravity="center_vertical"
                Android:layout_marginLeft="10dp"
                Android:text="Email"
                Android:id="@+id/tv_email"
                Android:textColor="#000000"
                Android:textSize="15dp" />

        </LinearLayout>

        <View
            Android:layout_width="match_parent"
            Android:layout_height="1dp"
            Android:background="#000000"></View>
    </LinearLayout>

    <LinearLayout
        Android:layout_width="match_parent"
        Android:layout_height="50dp"
        Android:layout_alignParentBottom="true"
        Android:layout_margin="10dp"
        Android:background="#E02F2F"
        Android:orientation="horizontal">

        <ImageView
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:id="@+id/iv_google"
            Android:src="@drawable/google_plus" />

        <TextView
            Android:layout_width="match_parent"
            Android:layout_height="match_parent"
            Android:layout_gravity="center"
            Android:id="@+id/tv_google"
            Android:gravity="center_vertical"
            Android:text="Sign in with Google"
            Android:textColor="#FFFFFF"
            Android:textSize="20dp" />

    </LinearLayout>
</RelativeLayout>

MainActivity.Java

package com.deepshikha.googlepluslogin;

import Android.app.ProgressDialog;
import Android.content.Intent;
import Android.support.annotation.NonNull;
import Android.support.v4.app.FragmentActivity;
import Android.support.v7.app.AppCompatActivity;
import Android.os.Bundle;
import Android.util.Log;
import Android.view.View;
import Android.widget.ImageView;
import Android.widget.TextView;
import Android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.Android.gms.auth.api.Auth;
import com.google.Android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.Android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.Android.gms.auth.api.signin.GoogleSignInResult;
import com.google.Android.gms.common.ConnectionResult;
import com.google.Android.gms.common.api.GoogleApiClient;
import com.google.Android.gms.common.api.ResultCallback;
import com.google.Android.gms.common.api.Status;
import com.google.Android.gms.tasks.OnCompleteListener;
import com.google.Android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {

    private static final int RC_SIGN_IN = 9001;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private GoogleApiClient mGoogleApiClient;
    ImageView iv_google;
    ProgressDialog dialog;
    ImageView iv_image;

    boolean boolean_google;
    TextView tv_name, tv_email, tv_google;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
        listener();

    }

    private void init() {

        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_email = (TextView) findViewById(R.id.tv_email);
        tv_google = (TextView) findViewById(R.id.tv_google);
        iv_google = (ImageView) findViewById(R.id.iv_google);
        iv_image = (ImageView)findViewById(R.id.iv_image);

        dialog = new ProgressDialog(MainActivity.this);
        dialog.setMessage("Loading..");
        dialog.setTitle("Please Wait");
        dialog.setCancelable(false);

        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("LoginActivity", "onAuthStateChanged:signed_in:" + user.getUid());
                } else {
                    // User is signed out
                    Log.d("LoginActivity", "onAuthStateChanged:signed_out");
                }
                // [START_EXCLUDE]
                updateUI(user);
                // [END_EXCLUDE]
            }
        };


        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(MainActivity.this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();
    }

    private void listener() {
        iv_google.setOnClickListener(this);
        tv_google.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.iv_google:
                break;
            case R.id.tv_google:
                if (boolean_google){
                    signOut();
                    tv_name.setText("");
                    tv_email.setText("");
                    boolean_google=false;
                    Glide.with(MainActivity.this).load(R.drawable.profileimage).into(iv_image);
                }else {
                    signIn();
                }
                break;
        }

    }

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

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

    @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
                // [START_EXCLUDE]
                updateUI(null);
                // [END_EXCLUDE]
            }
        }

    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d("LoginActivity", "firebaseAuthWithGoogle:" + acct.getId());
        // [START_EXCLUDE silent]
        try {

            dialog.show();
        } catch (Exception e) {

        }
        // [END_EXCLUDE]

        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("LoginActivity", "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("LoginActivity", "signInWithCredential", task.getException());
                            Toast.makeText(MainActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                        // [START_EXCLUDE]

                        try {

                            dialog.dismiss();
                        } catch (Exception e) {

                        }
                        // [END_EXCLUDE]
                    }
                });
    }

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

    private void signOut() {
        // Firebase sign out
        try {
            mAuth.signOut();

            // Google sign out
            Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                    new ResultCallback<Status>() {
                        @Override
                        public void onResult(@NonNull Status status) {
                            updateUI(null);
                        }
                    });
        } catch (Exception e) {

        }
    }

    private void updateUI(FirebaseUser user) {
        try {
            dialog.dismiss();
        } catch (Exception e) {

        }

        if (user != null) {
            String str_emailgoogle = user.getEmail();
            Log.e("Email", str_emailgoogle);
            tv_email.setText(str_emailgoogle);
            tv_name.setText(user.getDisplayName());
            boolean_google=true;
            tv_google.setText("Sign out from Google");

            Glide.with(MainActivity.this).load( user.getPhotoUrl()).into(iv_image);


            Log.e("Profile", user.getPhotoUrl() + "");

        } else {

        }
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        // An unresolvable error has occurred and Google APIs (including Sign-In) will not
        // be available.
        Log.d("LoginActivity", "onConnectionFailed:" + connectionResult);
        Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
    }
}
0
Deepshikha Puri