Android에서 Google Play 게임즈 서비스를 사용하여 인증

플레이어가 Google Play 게임즈 서비스를 사용하여 Firebase 기반 Android 게임에 로그인하도록 할 수 있습니다. Firebase를 통해 Google Play 게임즈 서비스 로그인을 사용하려면 우선 Google Play 게임즈에 플레이어를 로그인 처리하면서 OAuth 2.0 인증 코드를 요청합니다. 그런 다음 PlayGamesAuthProvider에 인증 코드를 전달하여 Firebase에 인증하는 데 사용할 수 있는 Firebase 사용자 인증 정보를 생성합니다.

시작하기 전에

Android 프로젝트 설정

  1. 아직 추가하지 않았다면 Android 프로젝트에 Firebase를 추가합니다.

  2. 모듈(앱 수준) Gradle 파일(일반적으로 <project>/<app-module>/build.gradle.kts 또는 <project>/<app-module>/build.gradle)에서 Firebase 인증 Android 라이브러리의 종속 항목을 추가합니다. 라이브러리 버전 관리 제어에는 Firebase Android BoM을 사용하는 것이 좋습니다.

    또한 Firebase 인증을 설정하는 과정에서 앱에 Google Play 서비스 SDK를 추가해야 합니다.

    Kotlin+KTX

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:32.3.1"))
    
        // Add the dependency for the Firebase Authentication library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-auth-ktx")
    // Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:20.7.0")
    }

    Firebase Android BoM을 사용하면 앱에서 항상 호환되는 Firebase Android 라이브러리 버전만 사용합니다.

    (대안) BoM을 사용하지 않고 Firebase 라이브러리 종속 항목을 추가합니다.

    Firebase BoM을 사용하지 않도록 선택한 경우에는 종속 항목 줄에 각 Firebase 라이브러리 버전을 지정해야 합니다.

    앱에서 여러 Firebase 라이브러리를 사용하는 경우 모든 버전이 호환되도록 BoM을 사용하여 라이브러리 버전을 관리하는 것이 좋습니다.

    dependencies {
        // Add the dependency for the Firebase Authentication library
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-auth-ktx:22.1.2")
    // Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:20.7.0")
    }

    Java

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:32.3.1"))
    
        // Add the dependency for the Firebase Authentication library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-auth")
    // Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:20.7.0")
    }

    Firebase Android BoM을 사용하면 앱에서 항상 호환되는 Firebase Android 라이브러리 버전만 사용합니다.

    (대안) BoM을 사용하지 않고 Firebase 라이브러리 종속 항목을 추가합니다.

    Firebase BoM을 사용하지 않도록 선택한 경우에는 종속 항목 줄에 각 Firebase 라이브러리 버전을 지정해야 합니다.

    앱에서 여러 Firebase 라이브러리를 사용하는 경우 모든 버전이 호환되도록 BoM을 사용하여 라이브러리 버전을 관리하는 것이 좋습니다.

    dependencies {
        // Add the dependency for the Firebase Authentication library
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-auth:22.1.2")
    // Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:20.7.0")
    }

Firebase 프로젝트 설정

  1. Firebase Console의 설정 페이지에서 게임의 SHA-1 디지털 지문을 설정합니다.

    Gradle signingReport 명령어를 사용하여 서명 인증서의 SHA 해시를 가져올 수 있습니다.

    ./gradlew signingReport

  2. Google Play 게임즈를 로그인 제공업체로 사용 설정합니다.

    1. 프로젝트의 웹 서버 클라이언트 ID와 클라이언트 보안 비밀번호를 찾습니다. Google Play 인증 서버에서는 이 웹 서버 클라이언트 ID로 Firebase 프로젝트를 식별합니다.

      이 값을 확인하는 방법은 다음과 같습니다.

      1. Google API 콘솔 사용자 인증 정보 페이지에서 Firebase 프로젝트를 엽니다.
      2. OAuth 2.0 클라이언트 ID 섹션에서 웹 클라이언트(Google 서비스에서 자동 생성) 세부정보 페이지를 엽니다. 이 페이지에 웹 서버 클라이언트 ID와 보안 비밀번호가 표시됩니다.
    2. Firebase Console에서 인증 섹션을 엽니다.

    3. 로그인 방법 탭에서 Play 게임즈 로그인 제공업체를 사용 설정합니다. API 콘솔에서 가져온 프로젝트의 웹 서버 클라이언트 ID와 클라이언트 보안 비밀번호를 지정해야 합니다.

Firebase 앱 정보로 Play 게임즈 서비스 구성

  1. Google Play Console에서 Google Play 앱을 열거나 만듭니다.

  2. 성장 섹션에서 Play 게임즈 서비스 > 설정 및 관리 > 구성을 클릭합니다.

  3. 예, 게임에서 이미 Google API를 사용하고 있습니다를 클릭하고 목록에서 Firebase 프로젝트를 선택한 후 사용을 클릭합니다.

  4. Play 게임즈 서비스 구성 페이지에서 사용자 인증 정보 추가를 클릭합니다.

    1. 게임 서버 유형을 선택합니다.
    2. OAuth 클라이언트 입력란에서 프로젝트의 웹 클라이언트 ID를 선택합니다. 이 ID는 Play 게임즈 로그인을 사용 설정할 때 지정한 클라이언트 ID와 일치해야 합니다.
    3. 변경사항을 저장합니다.
  5. Play 게임즈 서비스 구성 페이지에서 다시 사용자 인증 정보 추가를 클릭합니다.

    1. Android 유형을 선택합니다.
    2. OAuth 클라이언트 입력란에서 프로젝트의 Android 클라이언트 ID를 선택합니다. (Android 클라이언트 ID가 표시되지 않는 경우 Firebase Console에서 게임의 SHA-1 디지털 지문을 설정해야 합니다.)
    3. 변경사항을 저장합니다.
  6. 테스터 페이지에서 Play 스토어에 게임을 출시하기 전에 게임에 로그인할 수 있어야 하는 사용자의 이메일 주소를 추가합니다.

게임에 Play 게임즈 로그인 통합

먼저 앱에 Play 게임즈 로그인을 통합합니다. 자세한 안내는 Android 게임에 로그인을 참조하세요.

통합 코드에서 GoogleSignInOptions 객체를 작성할 때 DEFAULT_GAMES_SIGN_IN 구성을 사용하고 requestServerAuthCode를 호출합니다.

Kotlin+KTX

val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
    .requestServerAuthCode(getString(R.string.default_web_client_id))
    .build()

Java

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
        .requestServerAuthCode(getString(R.string.default_web_client_id))
        .build();

requestServerAuthCode 메서드에 웹 서버 클라이언트 ID를 전달해야 합니다. 이 ID는 Firebase Console에서 Play 게임즈 로그인을 사용 설정할 때 제공한 ID입니다.

Firebase에 인증

앱에 Play 게임즈 로그인을 추가한 후에는 플레이어가 Play 게임즈로 로그인할 때 확인되는 Google 계정 사용자 인증 정보를 사용하도록 Firebase를 설정해야 합니다.

  1. 우선 다음과 같이 로그인 작업의 onCreate 메서드에서 FirebaseAuth 객체의 공유 인스턴스를 가져옵니다.

Kotlin+KTX

private lateinit var auth: FirebaseAuth
// ...
// Initialize Firebase Auth
auth = Firebase.auth

Java

private FirebaseAuth mAuth;
// ...
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
  1. 작업을 초기화할 때 플레이어가 이미 Firebase로 로그인했는지 확인합니다.

Kotlin+KTX

override fun onStart() {
    super.onStart()
    // Check if user is signed in (non-null) and update UI accordingly.
    val currentUser = auth.currentUser
    updateUI(currentUser)
}

Java

@Override
public void onStart() {
    super.onStart();
    // Check if user is signed in (non-null) and update UI accordingly.
    FirebaseUser currentUser = mAuth.getCurrentUser();
    updateUI(currentUser);
}
If the player isn't signed in, present the player with your game's
signed-out experience, including the option to sign in.
  1. 플레이어가 자동 또는 대화형으로 Play 게임즈에 로그인하면 GoogleSignInAccount 객체에서 인증 코드를 가져와 Firebase 사용자 인증 정보로 교환하고 이 사용자 인증 정보를 사용하여 Firebase에 인증합니다.

Kotlin+KTX

// Call this both in the silent sign-in task's OnCompleteListener and in the
// Activity's onActivityResult handler.
private fun firebaseAuthWithPlayGames(acct: GoogleSignInAccount) {
    Log.d(TAG, "firebaseAuthWithPlayGames:" + acct.id!!)

    val auth = Firebase.auth
    val credential = PlayGamesAuthProvider.getCredential(acct.serverAuthCode!!)
    auth.signInWithCredential(credential)
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                // Sign in success, update UI with the signed-in user's information
                Log.d(TAG, "signInWithCredential:success")
                val user = auth.currentUser
                updateUI(user)
            } else {
                // If sign in fails, display a message to the user.
                Log.w(TAG, "signInWithCredential:failure", task.exception)
                Toast.makeText(
                    baseContext,
                    "Authentication failed.",
                    Toast.LENGTH_SHORT,
                ).show()
                updateUI(null)
            }

            // ...
        }
}

Java

// Call this both in the silent sign-in task's OnCompleteListener and in the
// Activity's onActivityResult handler.
private void firebaseAuthWithPlayGames(GoogleSignInAccount acct) {
    Log.d(TAG, "firebaseAuthWithPlayGames:" + acct.getId());

    final FirebaseAuth auth = FirebaseAuth.getInstance();
    AuthCredential credential = PlayGamesAuthProvider.getCredential(acct.getServerAuthCode());
    auth.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 = auth.getCurrentUser();
                        updateUI(user);
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(MainActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                        updateUI(null);
                    }

                    // ...
                }
            });
}

signInWithCredential 호출이 성공하면 getCurrentUser 메서드를 사용하여 사용자의 계정 데이터를 가져올 수 있습니다.

다음 단계

사용자가 처음으로 로그인하면 신규 사용자 계정이 생성되어 사용자의 Play 게임즈 ID에 연결됩니다. 이 신규 계정은 Firebase 프로젝트에 저장되며 프로젝트의 모든 앱에서 사용자 식별에 사용할 수 있습니다.

게임에서 FirebaseUser 객체로부터 사용자의 Firebase UID를 가져올 수 있습니다.

Kotlin+KTX

val user = auth.currentUser
user?.let {
    val playerName = it.displayName

    // The user's Id, unique to the Firebase project.
    // Do NOT use this value to authenticate with your backend server, if you
    // have one; use FirebaseUser.getIdToken() instead.
    val uid = it.uid
}

Java

FirebaseUser user = mAuth.getCurrentUser();
String playerName = user.getDisplayName();

// The user's Id, unique to the Firebase project.
// Do NOT use this value to authenticate with your backend server, if you
// have one; use FirebaseUser.getIdToken() instead.
String uid = user.getUid();

Firebase 실시간 데이터베이스와 Cloud Storage 보안 규칙의 auth 변수에서 로그인한 사용자의 고유 사용자 ID를 가져온 후 이 ID를 통해 사용자가 액세스할 수 있는 데이터를 제어할 수 있습니다.

사용자의 Play 게임즈 플레이어 정보를 가져오거나 Play 게임즈 서비스에 액세스하려면 Google Play 게임즈 SDK에서 제공하는 API를 사용합니다.

사용자를 로그아웃시키려면 FirebaseAuth.signOut()을 호출합니다.

Kotlin+KTX

Firebase.auth.signOut()

Java

FirebaseAuth.getInstance().signOut();