새소식

Android Studio[JAVA]

소셜 로그인 (구글, Google 편)

  • -

큰 순서는 다음과 같다.

 

1. build.gradle (app)에서 compileSdk을 33으로 맞춰주세요.

(본인 컴퓨터에서 잘 돌아간다면 상관없다.) 
2. build.gradle (app)에서 다음을 입력!

implementation 'com.google.android.gms:play-services-auth:20.5.0'


3. 안드로이드 스튜디오 터미널에서 ./gradlew signingReport 를 입력하면 로컬 PC의 SHA1 지문을 얻을 수 있다.
4. 구글 API 콘솔에서 프로젝트 생성 후, 좌측 햄버거 버튼 - API 및 서비스 - 

   사용자 인증 정보로 들어가서, 상단의 사용자 정보 추가를 클릭 후, Oauth Client 클릭한다.
5. 안드로이드 선택 후, 해당 프로젝트의 패키지 이름과 3번에서 얻은 SHA1 지문을 입력한다.
6. 구글 API 콘솔에서 Oauth Client ID를 복사하여 프로젝트의 strings.xml 파일에 붙여넣는다.
형식 : <string name="server_client_id">YOUR_SERVER_CLIENT_ID</string>

(res - values - strings.xml 에 [형식]에 맞춰서 입력해주면 된다.)
7. 주석 보며 코드 확인

< MainActivity.xml 전체 코드 >

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:gravity="center"
    tools:context=".MainActivity">

    <com.google.android.gms.common.SignInButton
        android:id="@+id/sign_in_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:tooltipText=""
        android:layout_weight="1"
        android:onClick="onClick"/>

    <Button
        android:id="@+id/logoutBt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="로그아웃"
        android:textColor="@color/black"
        android:backgroundTint="@color/white"
        android:layout_weight="1"
        android:onClick="onClick"/>
</LinearLayout>

 

< MainActivty.java 전체 코드 >

package com.example.test_google_login;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.Task;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    // Google Sign in API와 호출할 구글 로그인 클라이언트
    GoogleSignInClient mGoogleSignInClient;
    private static final String TAG = "MainActivity";
    private final int check_signIn = 111;

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

        SignInButton btn_login = findViewById(R.id.sign_in_button);
        Button btn_logout = findViewById(R.id.logoutBt);
        btn_login.setOnClickListener(this);
        btn_logout.setOnClickListener(this);

        // 구글로그인

        // 앱에 필요한 사용자 데이터를 요청하도록 로그인 옵션을 설정.
        // DEFAULT_SIGN_IN parameter는 유저 ID 및 기본적인 프로필 정보를 요청하는데 사용된다.
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                // 백엔드에서 사용자를 식별할 수 있는 사용자 ID 토큰 요청
                // 사용자의 기본 프로필(이름, 사진 ,URL 등)이 포함되므로 추가 호출할 필요 X
                .requestIdToken(getString(R.string.server_client_id))
                // 프론트에서 이메일 주소 요청
                .requestEmail()
                .build();

        // 위에서 만든 GoogleSignInOptions를 사용하여 GoogleSignInClient 객체를 생성한다.
        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        // 사용자가 이미 Google로 앱에 로그인했는지 확인한다.
        GoogleSignInAccount gsa = GoogleSignIn.getLastSignedInAccount(this);

        // 로그인이 되어있는 경우
        if (gsa != null && gsa.getId() != null) {
            // 해당 처리를 해주면 된다
            Intent intent = new Intent(getApplicationContext(), loginSuccess.class);
            startActivity(intent);
        }
    }

    private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
        try {
            GoogleSignInAccount acct = completedTask.getResult(ApiException.class);

            if (acct != null) {
                String personName = acct.getDisplayName();      // 이름
                String personGivenName = acct.getGivenName();   // 성
                String personFamilyName = acct.getFamilyName(); // ?
                String personEmail = acct.getEmail();           // 이메일 주소
                String personId = acct.getId();                 // ?
                Uri personPhoto = acct.getPhotoUrl();           // 프로필 URL
                String AT = acct.getIdToken();

                Log.d(TAG, "handleSignInResult:personName "+personName);
                Log.d(TAG, "handleSignInResult:personGivenName "+personGivenName);
                Log.d(TAG, "handleSignInResult:personEmail "+personEmail);
                Log.d(TAG, "handleSignInResult:personId "+personId);
                Log.d(TAG, "handleSignInResult:personFamilyName "+personFamilyName);
                Log.d(TAG, "handleSignInResult:personPhoto "+personPhoto);
                Log.d(TAG, "ACCESS TOKEN" + AT);
            }
        } catch (ApiException e) {
            // The ApiException status code indicates the detailed failure reason.
            // Please refer to the GoogleSignInStatusCodes class reference for more information.
            Log.e(TAG, "signInResult:failed code=" + e.getStatusCode());

        }
    }

    public void onClick(View view) {
        // 버튼의 id를 가져온다.
        switch(view.getId())
        {
            case R.id.sign_in_button:
                // 로그인 버튼 클릭 시
                signIn();
                break;
            case R.id.logoutBt:
                //로그 아웃 버튼
                mGoogleSignInClient.signOut()
                        .addOnCompleteListener(this, task -> {
                            Log.d(TAG, "onClick:logout success ");
                            mGoogleSignInClient.revokeAccess()
                                    .addOnCompleteListener(this, task1 -> Log.d(TAG, "onClick:revokeAccess success "));
                        });
                Toast.makeText(getApplicationContext(), "로그아웃 되었습니다.", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private void signIn() {
        //getSignInIntent로 로그인 인텐트를 만든다.
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        // 인텐트 시작하여 로그인 버튼 탭을 처리한다.
        startActivityForResult(signInIntent, check_signIn);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
        // 사용자가 로그인을 성공하면 사용자의 GoogleSignInAccount 객체를 가져올 수 있다.
        if (requestCode == check_signIn) {
            // The Task returned from this call is always completed, no need to attach
            // a listener.
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            // 정보 띄워주기 메서드 실행
            handleSignInResult(task);
            Intent intent = new Intent(getApplicationContext(), loginSuccess.class);
            startActivity(intent);
        }
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }
}

- Intent는 로그인이 잘 되었을 때 확인하기 위해서 loginSuccess 액티비티를 하나 만들어주었다.

 

[결과 화면]

- 초기 화면

- sign in 버튼 클릭, 로그인 성공 시

 

 


참고 자료 : 자료에서 많은 것을 얻을 수 있었다..대박!
(1) 구글 로그인 연동 참고 및 실제 앱 서비스 관련 참고


https://blog.naver.com/nakim02/221409188247

 

[Android Studio] Google Sign in 삽질.

기본 구성은 간단하다. 이거대로 따라하면 된다: https://developers.google.com/identity/sign-...

blog.naver.com

 

(2) 백엔드 구글 로그인 서버 연동 참고 

https://developers.google.com/identity/sign-in/android/backend-auth?hl=k

 

백엔드 서버로 인증  |  Google Developers

이 페이지는 Cloud Translation API를 통해 번역되었습니다. Switch to English 백엔드 서버로 인증 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 백엔드 서버와 통신

developers.google.com

 

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.