简体   繁体   English

使用Google Play游戏进行Firebase身份验证

[英]Firebase Authentication with Google Play Games

I am creating a game for android. 我正在为Android创建游戏。 Each user needs to be authenticated. 每个用户都需要进行身份验证。

Currently, when a new user launches the game, it requests an identification code from my server, and stores it to SharedPreferences. 当前,当新用户启动游戏时,它将向我的服务器请求一个识别码,并将其存储到SharedPreferences中。 Next time user launches the game, it uses this stored identification code to authenticate. 下次用户启动游戏时,它将使用此存储的标识码进行身份验证。 The problem is, when user clears data of this app, there's no way he can get his ID back, so he lost his progress forever. 问题是,当用户清除此应用程序的数据时,他无法找回自己的ID,因此他永远失去了自己的进步。

Is there a way how to generate something like Identification code which is unique and always the same for one player using Firebase Play games auth method? 有没有一种方法可以使用Firebase Play游戏auth方法生成一个唯一且始终相同的识别码之类的东西?

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
                .requestServerAuthCode("MyCID")
                .build();

        mAuth = FirebaseAuth.getInstance();
        super.onCreate(savedInstanceState);
        final FirebaseAuth auth = FirebaseAuth.getInstance();
        AuthCredential credential = PlayGamesAuthProvider.getCredential("MyCID");
        auth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            currentUser = auth.getCurrentUser();
                        } else {
                            Toast.makeText(MainActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
        if (currentUser == null) {
            cu = "NO UID";
        } else {
            cu = currentUser.getUid();
        }

I tried this code (Where is MyCID: I used the CID from the image below), but no Google Play Games pop-up is shown, I get Authentication Failed toast and cu is set to "NO UID". 我尝试了这段代码(MyCID在哪里:我使用了下图中的CID),但是没有显示Google Play游戏弹出窗口,我收到了Authentication Failed Toast,并且cu设置为“ NO UID”。

MyCID

Can someone explain how does this work please? 有人可以解释一下如何工作吗?


EDIT 编辑

Thanks to @crysxd , My app now shows the green google play games popup. 感谢@crysxd,我的应用程序现在显示绿色的Google Play游戏弹出窗口。 But instead of expected "Select an account" popup, as I see in other games which uses google games sign in, I get an error, which says "com.google.android.gms.common.api.ApiException: 4:". 但是我没有看到预期的“选择帐户”弹出窗口,而是看到“ com.google.android.gms.common.api.ApiException:4:”,这是我在使用Google游戏登录的其他游戏中看到的。

Is there a function which I need to run to show this dialog? 我需要运行一个函数来显示此对话框吗? Am I missing something or just I have incorrectly configured the game in google play console? 我是否缺少某些东西,或者只是我在Google Play控制台中错误地配置了游戏?

My current code: link 我当前的代码: 链接

You are skipping an essential step here. 您在这里跳过了必要的步骤。 The Firebase docs are usually very good, but the Play sign in is poorly described. Firebase文档通常非常好,但是Play登录的描述很少。

You got the first step right: You need to set up GoogleSignInOptions but you miss to pass them to a GoogleSignInClient . 您迈出了第一步:您需要设置GoogleSignInOptions但是错过了将它们传递给GoogleSignInClient

  • Create a client in onCreate : onCreate创建一个客户端:

     private static final int RC_SIGN_IN = 543; private GoogleSignInClient mGoogleSignInClient; public void onCreate(Bundle savedInstancestate) { super.onCreate(savedInstancestate) // ... GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN) .requestServerAuthCode("MyCID") .build(); mGoogleSignInClient= GoogleSignIn.getClient(this, gso) } 
  • Call this method when the sign in button is clicked or you want to start sign in. This will cause the sign in dialog to be shown. 单击登录按钮或要开始登录时,请调用此方法。这将导致显示登录对话框。

     private void signIn() { Intent signInIntent = mGoogleSignInClient.getSignInIntent(); startActivityForResult(signInIntent, RC_SIGN_IN); } 
  • Get the sign in response and handle it 得到签收回应并处理

     @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) { Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { // Google Sign In was successful, authenticate with Firebase GoogleSignInAccount account = task.getResult(ApiException.class); firebaseAuthWithGoogle(account); } catch (ApiException e) { // Google Sign In failed, update UI appropriately Log.w(TAG, "Google sign in failed", e); } } } 
  • Finally, your code comes into play. 最后,您的代码发挥作用。 Now we have the GoogleSignInAccount which is required to call PlayGamesAuthProvider.getCredential(...) . 现在我们有了GoogleSignInAccount ,它是调用PlayGamesAuthProvider.getCredential(...)所必需的。 You passed your Client ID here, but that's the wrong thing. 您在此处传递了客户ID,但这是错误的。 This is how it works: You give your client ID to Google just to tell them who (or which app) you are. 它是这样工作的:您将客户ID提供给Google只是为了告诉他们您是谁(或哪个应用程序)。 They will let the user sign in and give you a special token ("id token") which Firebase can then use to get information about the user from Google Play Games. 他们将允许用户登录并为您提供一个特殊的令牌(“ id令牌”),然后Firebase可以使用该令牌从Google Play游戏获取有关用户的信息。 And that's the token you need to give to Firebase here: 这就是您需要在此处给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) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success"); FirebaseUser user = mAuth.getCurrentUser(); updateUI(user); } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithCredential:failure", task.getException()); Snackbar.make(findViewById(R.id.main_layout), "Authentication Failed.", Snackbar.LENGTH_SHORT).show(); updateUI(null); } // ... } }); } 

Hope that helps! 希望有帮助! You can find the entire code referenced in the docs here and here (these are the files they show the snippets from in the docs). 您可以在此处此处找到文档中引用的完整代码(这些是它们在文档中显示摘录的文件)。

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

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