안드로이드 앱에서 구글 로그인 연동하기

By | 2024년 12월 19일
Table of Contents

안드로이드 앱에서 구글 로그인 연동하기

참조

Google Firebase Console

https://console.firebase.google.com/

프로젝트 설정 > 일반 > SHA-1 설정 (내 프로젝트의 SHA-1 가져와서 저장)

SHA1, SHA-256 확인하는 법과 signingReport gradle이 없을 때 해결 방법

Authentication > Google 로그인 추가 설정

google-services.json 에 아래와 같은 내용이 있어야 한다.

      "oauth_client": [
        {
          "client_id": "XXXXXXXXXXXXX.apps.googleusercontent.com",
          "client_type": 1,
          "android_info": {
            "package_name": "XXXXXXXXXXX",
            "certificate_hash": "XXXXXXXXXXXXXX"
          }
        },
        {
          "client_id": "XXXXXXXXXXXXXX.apps.googleusercontent.com",
          "client_type": 3
        }
      ],

최신 버전의 google-services.json을 app 폴더에 갱신

테스트 후 구글 플레이에서 설치한 앱의 경우,
구글이 제공하는 서명키를 등록해 주어야 한다.

Google Cloud Console

https://console.cloud.google.com/apis/

OAuth 동의 화면 작성
OAuth 2.0 클라이언트 ID 추가
(웹 애플리케이션 O)
(android X)

왠지… Authentication > Google 로그인 추가 설정 부분이 이걸 한 후에 해야 할듯…

앱 단위 gradle

plugins {
    // ......
    id("com.google.gms.google-services")
}

dependencies {
    // ......
    implementation "androidx.credentials:credentials:1.3.0"
    implementation "androidx.credentials:credentials-play-services-auth:1.3.0"
    implementation libs.googleid

    implementation 'com.google.gms:google-services:4.4.2'
    implementation 'com.google.firebase:firebase-auth:23.1.0'
    implementation platform('com.google.firebase:firebase-bom:32.0.0')
    implementation 'com.google.android.gms:play-services-auth:21.3.0'
}

프로젝트 단위 gradle

buildscript {
    repositories {
        google()
        mavenCentral()
    }
}

plugins {
    alias(libs.plugins.android.application) apply false
    id("com.google.gms.google-services") version "4.4.2" apply false
}

코드 작성

    private void setupLogin() {
        credentialManager = CredentialManager.create(this);
        findViewById(R.id.sign_in_button).setOnClickListener(v -> signIn());
    }

    private void signIn() {
        GetCredentialRequest request = new GetCredentialRequest.Builder()
                .addCredentialOption(new GetGoogleIdOption.Builder()
                        .setServerClientId(getString(R.string.default_web_client_id))
                        .build())
                .build();

        credentialManager.getCredential(
                this,
                request,
                new Continuation<GetCredentialResponse>() {
                    @NonNull
                    @Override
                    public CoroutineContext getContext() {
                        return EmptyCoroutineContext.INSTANCE;
                    }

                    @Override
                    public void resumeWith(@NonNull Object result) {
                        try {
                            if (result instanceof GetCredentialResponse) {
                                GetCredentialResponse response = (GetCredentialResponse) result;
                                if (response.getCredential() instanceof GoogleIdTokenCredential) {
                                    GoogleIdTokenCredential credential =
                                            (GoogleIdTokenCredential) response.getCredential();
                                    String idToken = credential.getIdToken();
                                    String id = credential.getId();

                                    runOnUiThread(() -> {
                                        Log.d(TAG, "ID Token: " + idToken);
                                        Log.d(TAG, "Email: " + id);
                                        Toast.makeText(MainActivity.this,
                                                "Google Sign-In Successful\nEmail: " + id,
                                                Toast.LENGTH_SHORT).show();
                                    });
                                }
                            }
                        } catch (Exception e) {
                            runOnUiThread(() -> {
                                Log.e(TAG, "Google Sign-In Failed: " + e.getMessage());
                                Toast.makeText(MainActivity.this, "Google Sign-In Failed",
                                        Toast.LENGTH_SHORT).show();
                            });
                        }
                    }
                }
        );
    }

정상적으로 설정이 된 경우, R.string.default_web_client_id 가 오류없이 인식된다.

답글 남기기