简体   繁体   English

使用google firebase身份验证对android进行身份验证

[英]Authenticating android with google firebase authentication

I am trying to authenticate my app with google sign in. 我正在尝试通过谷歌登录验证我的应用程序。

When I try to do this I get the error Google Sign In failed. Status = Status{statusCode=DEVELOPER_ERROR, resolution=null} 当我尝试这样做时,我收到错误 Google Sign In failed. Status = Status{statusCode=DEVELOPER_ERROR, resolution=null} Google Sign In failed. Status = Status{statusCode=DEVELOPER_ERROR, resolution=null}

I have generated a SHA1 key and have the Google Auth enabled on the FireBase console. 我已生成SHA1密钥并在FireBase控制台上启用了Google Auth。

I am a beginner with the authentication side of Android. 我是Android的身份验证方面的初学者。

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

private FirebaseAuth mFirebaseAuth;
private ProgressBar progressBar;
private ProgressDialog mProgressDialog;
private GoogleApiClient mGoogleApiClient;
private static final String TAG = "RegisterActivity";

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

    // Get FireBase mFirebaseAuth instance
    mFirebaseAuth = FirebaseAuth.getInstance();

    if (mFirebaseAuth.getCurrentUser() != null) {
        Log.e("45hh", "User logged in already...");
        startActivity(new Intent(RegisterActivity.this, MainActivity.class));
    }


    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestScopes(new Scope(Scopes.PLUS_LOGIN))
            .requestScopes(new Scope(Scopes.PLUS_ME))
            .requestEmail()
            .build();
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

    final EditText txtEmail = (EditText) findViewById(R.id.txtEmail);
    final EditText txtPassword = (EditText) findViewById(R.id.txtPassword);
    Button btnRegister = (Button) findViewById(R.id.btnRegister);
    Button btnGSignin = (Button) findViewById(R.id.btnGSignin);
    TextView txtAlreadyHaveAccount = (TextView) findViewById(R.id.txtAlreadyHaveAccount);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String email = txtEmail.getText().toString().trim();
            String password = txtPassword.getText().toString().trim();

            if (TextUtils.isEmpty(email)) {
                Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
                return;
            } else if (TextUtils.isEmpty(password)) {
                Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
                return;
            }

            if (password.length() < 6) {
                Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
                return;
            }

            progressBar.setVisibility(View.VISIBLE);
            // Create user
            mFirebaseAuth.createUserWithEmailAndPassword(email, password)
                    .addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if (task.isSuccessful()) {
                                Toast.makeText(RegisterActivity.this, "Successfully registered!", Toast.LENGTH_SHORT).show();
                                progressBar.setVisibility(View.GONE);
                                startActivity(new Intent(RegisterActivity.this, MainActivity.class));
                                finish();
                            } else {
                                Toast.makeText(RegisterActivity.this, "Authentication failed. " + task.getResult(),
                                        Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }
    });

    btnGSignin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            signIn();
        }
    });

    txtAlreadyHaveAccount.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
        }
    });
}

private void handleFirebaseAuthResult(AuthResult authResult) {
    if (authResult != null) {
        // Welcome the user
        FirebaseUser user = authResult.getUser();
        Toast.makeText(this, "Welcome " + user.getEmail(), Toast.LENGTH_SHORT).show();

        // Go back to the main activity
        startActivity(new Intent(this, MainActivity.class));
    }
}

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

@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 == 9001) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = result.getSignInAccount();
            firebaseAuthWithGoogle(account);
        } else {
            if(mProgressDialog!=null){
                hideProgressDialog();
            }
            // Google Sign In failed
            Log.e(TAG, "Google Sign In failed. Status = " + result.getStatus());
        }
    }
}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG, "firebaseAuthWithGooogle:" + acct.getId());
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mFirebaseAuth.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(RegisterActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(RegisterActivity.this, "Authentication Success. Please Wait",
                                Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(RegisterActivity.this, MainActivity.class));
                        finish();
                    }
                    hideProgressDialog();
                }
            });
}

public void showProgressDialog() {
    if (mProgressDialog == null) {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(true);
    }

    mProgressDialog.show();
}

public void hideProgressDialog() {
    if (mProgressDialog != null && mProgressDialog.isShowing()) {
        mProgressDialog.dismiss();
    }
}

@Override
public void onClick(View v) {

}

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

The reason this is not working is because the ClientID was not specified. 这不起作用的原因是因为未指定ClientID。 This is how it should be done: 这是应该如何做到的:

private static final String googleClientID = "Enter-ClientID-Here";

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(googleClientID)
            .requestEmail()
            .build();

You have to get your client ID from here: (Go to the FireBase Console -> Authentication -> Sign-In Method -> Google -> Hit the Web SDK configuration dropdown -> Web Client ID) 您必须从此处获取客户端ID :(转到FireBase控制台 - >身份验证 - >登录方法 - > Google - >点击Web SDK配置下拉列表 - > Web客户端ID

Google ClientID位置

PS Make sure you add the following permissions to you manifest PS确保向清单添加以下权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />

Hope this helps someone. 希望这有助于某人。

Just Follow these Steps for Google SignIn: 只需按照以下步骤操作Google SignIn:

1.) Create a Project at Google Developers Console 1.)在Google Developers Console中创建项目

Log in to Google Plus account and click on create project. 登录Google Plus帐户,然后单击“创建项目”。 Creating google project 创建谷歌项目

2.) Fill the details according to your choice, Then 2.)根据您的选择填写详细信息,然后

Now we need a configuration file for our android app.Select your app we just created on developer console. 现在我们需要一个Android应用程序的配置文件。选择我们刚刚在开发者控制台上创建的应用程序。 And write the package name of your android studio project you had created. 并编写您创建的android studio项目的包名称。 Finally choose country and click on continue. 最后选择国家,然后单击继续。

3.) Hit this command to Cmd for finding the SHA1 key. 3.)将此命令命令到Cmd以查找SHA1密钥。

For windows: 对于Windows:

keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

For Linux: 对于Linux:

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

Copy the SHA1 and paste it to the Enable Google Services Page. 复制SHA1并将其粘贴到“启用Google服务”页面。

Now click on Enable Google Signin. 现在点击启用Google登录。 And click on Continue to Generate Configuration Files. 然后单击继续以生成配置文件。 Now click on download google-services.json to get your configuration file. 现在点击下载google-services.json获取配置文件。 Now come to android studio. 现在来到android工作室。

Copy the json configuration file (you just downloaded) and paste it inside your google login android studio project (Inside app/ directory). 复制json配置文件(您刚刚下载)并将其粘贴到您的google登录android studio项目(Inside app / directory)中。 Like this configuration file 喜欢这个配置文件

Open the Top Level build.gradle file and add the following line inside dependencies. 打开顶级build.gradle文件,并在依赖项中添加以下行。

classpath 'com.google.gms:google-services:1.5.0-beta2'

Inside build.gradle file add the following dependencies and sync your google login android project. 在build.gradle文件中添加以下依赖项并同步您的google登录android项目。

compile 'com.google.android.gms:play-services-auth:8.3.0'
    compile 'com.mcxiaoke.volley:library-aar:1.0.0' // this is for fetching the profile image of the user

Now come to activity_main.xml. 现在来到activity_main.xml。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <com.google.android.gms.common.SignInButton
        android:id="@+id/sign_in_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/profileImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:text="Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textViewName"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


    <TextView
        android:text="email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


    <TextView
        android:id="@+id/textViewEmail"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Now come to MainActivity.java and write the following code. 现在来MainActivity.java并编写以下代码。

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
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.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;

import org.w3c.dom.Text;

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

    //Signin button
    private SignInButton signInButton;

    //Signing Options
    private GoogleSignInOptions gso;

    //google api client
    private GoogleApiClient mGoogleApiClient;

    //Signin constant to check the activity result
    private int RC_SIGN_IN = 100;

    //TextViews
    private TextView textViewName;
    private TextView textViewEmail;
    private NetworkImageView profilePhoto;

    //Image Loader
    private ImageLoader imageLoader;

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

        //Initializing Views
        textViewName = (TextView) findViewById(R.id.textViewName);
        textViewEmail = (TextView) findViewById(R.id.textViewEmail);
        profilePhoto = (NetworkImageView) findViewById(R.id.profileImage);

        //Initializing google signin option
        gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

        //Initializing signinbutton
        signInButton = (SignInButton) findViewById(R.id.sign_in_button);
        signInButton.setSize(SignInButton.SIZE_WIDE);
        signInButton.setScopes(gso.getScopeArray());

        //Initializing google api client
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();


        //Setting onclick listener to signing button
        signInButton.setOnClickListener(this);
    }


    //This function will option signing intent
    private void signIn() {
        //Creating an intent
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);

        //Starting intent for result
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //If signin
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            //Calling a new function to handle signin
            handleSignInResult(result);
        }
    }


    //After the signing we are calling this function
    private void handleSignInResult(GoogleSignInResult result) {
        //If the login succeed
        if (result.isSuccess()) {
            //Getting google account
            GoogleSignInAccount acct = result.getSignInAccount();

            //Displaying name and email
            textViewName.setText(acct.getDisplayName());
            textViewEmail.setText(acct.getEmail());

            //Initializing image loader
            imageLoader = CustomVolleyRequest.getInstance(this.getApplicationContext())
                    .getImageLoader();

            imageLoader.get(acct.getPhotoUrl().toString(),
                    ImageLoader.getImageListener(profilePhoto,
                            R.mipmap.ic_launcher,
                            R.mipmap.ic_launcher));

            //Loading image
            profilePhoto.setImageUrl(acct.getPhotoUrl().toString(), imageLoader);

        } else {
            //If login fails
            Toast.makeText(this, "Login Failed", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onClick(View v) {
        if (v == signInButton) {
            //Calling signin
            signIn();
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }
}

For loading image from URL I have used a Custom Volley Request.For the custom volley request you have to create the following class. 为了从URL加载图像,我使用了自定义排球请求。对于自定义排球请求,您必须创建以下类。

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.ImageLoader;


public class CustomVolleyRequest {

    private static CustomVolleyRequest customVolleyRequest;
    private static Context context;
    private RequestQueue requestQueue;
    private ImageLoader imageLoader;


    private CustomVolleyRequest(Context context) {
        this.context = context;
        this.requestQueue = getRequestQueue();

        imageLoader = new ImageLoader(requestQueue,
                new ImageLoader.ImageCache() {
                    private final LruCache<String, Bitmap>
                            cache = new LruCache<String, Bitmap>(20);

                    @Override
                    public Bitmap getBitmap(String url) {
                        return cache.get(url);
                    }

                    @Override
                    public void putBitmap(String url, Bitmap bitmap) {
                        cache.put(url, bitmap);
                    }
                });
    }

    public static synchronized CustomVolleyRequest getInstance(Context context) {
        if (customVolleyRequest == null) {
            customVolleyRequest = new CustomVolleyRequest(context);
        }
        return customVolleyRequest;
    }

    public RequestQueue getRequestQueue() {
        if (requestQueue == null) {
            Cache cache = new DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024);
            Network network = new BasicNetwork(new HurlStack());
            requestQueue = new RequestQueue(cache, network);
            requestQueue.start();
        }
        return requestQueue;
    }

    public ImageLoader getImageLoader() {
        return imageLoader;
    }

Now add internet permission to your manifest and run your google login android application. 现在为您的清单添加互联网权限并运行您的谷歌登录Android应用程序。

This,is all the full process for G-SignIn Authentication !!! 这就是G-SignIn认证的全部过程!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM