새소식

Android/Firebase

[Firebase] Authentication - 구글 로그인 간단하게 구현해보기

  • -

안드로이드 로고

Firebase에서 제공하는 Authentication에서 구글 로그인을 간단하게 구현해 보았습니다. 
우선 Firebase와 안드로이드 프로젝트를 연결해야 합니다!!! 

 

Firebase와 Android 프로젝트 연동하기

이번 글에서는 Firebase와 안드로이드 프로젝트를 연동하는 것을 보여드리겠습니다. 1. Firebase 콘솔 접속 https://console.firebase.google.com/?hl=ko 로그인 - Google 계정 이메일 또는 휴대전화 accounts.google.com 2

dong-hyeok.tistory.com


 

1. Firebase에 본인이 만든 프로젝트에 접속하면 화면 좌측에 다음과 같이 확인하실 수 있습니다.  

파이어베이스 인증 라이브러리 선택 이미지

 

 

 

2. Authentication 클릭하신 후 Sign-in method를 클릭하시면 여러 로그인 방법을 제공하는 것을 확인하실 수 있습니다. 

파이어베이스 로그인 종류

구글을 클릭하시면 다음과 같은 화면이 나타납니다. 

아래 "사용 설정"을 선택하시면 다음과 같은 입력창이 보입니다. 

Firebase 구글 로그인

저장을 하면 다음과 같습니다. 

파이어베이스 구글 로그인 등록

 

 

 

 

3. 안드로이드 프로젝트에 Firebase 인증을 수행해야 합니다. 

[ gradle Module ]

dependencies {
    // Import the BoM for the Firebase platform
    implementation platform('com.google.firebase:firebase-bom:31.1.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.4.0'
}

그리고 안드로이드 Manifest 파일에 인터넷 권한을 추가합니다. 

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

 

 

 

 

4. 안드로이드 프로젝트에 코드 구현 

https://firebase.google.com/docs/auth/android/google-signin?hl=ko

 

Android에서 Google로 인증,Android에서 Google로 인증  |  Firebase 인증

Firebase Summit에서 발표된 모든 내용을 살펴보고 Firebase로 앱을 빠르게 개발하고 안심하고 앱을 실행하는 방법을 알아보세요. 자세히 알아보기 이 페이지는 Cloud Translation API를 통해 번역되었습니

firebase.google.com

코드는 firebase 공식 문서를 참고하시면 각 메서드의 상세한 정보를 확인하실 수 있습니다. 

 

아래 코드는 로그인만 구현한 코드입니다. 
만약 로그아웃과 회원탈퇴를 구현하시려면 로그인 후 전환되는 화면에 로그아웃, 회원탈퇴 버튼을 각각 생성하시고 해당 함수 SignOut( ), revokeAccess( )를 호출하시면 됩니다. 

public class LoginActivity extends AppCompatActivity {

    private SignInButton signInButton;
    private GoogleSignInClient mGoogleSignInClient;
    private FirebaseAuth mAuth;
    private ActivityResultLauncher<Intent> activityResultLauncher;

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

        init();

        signInButton = findViewById(R.id.sign_in_button);
        signInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signIn();
            }
        });
    }
    private void init(){
        activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode()== Activity.RESULT_OK){
                            Intent intent = result.getData();
                            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(intent);
                            try {
                                // Google Sign In was successful, authenticate with Firebase
                                GoogleSignInAccount account = task.getResult(ApiException.class);
                                Toast.makeText(getApplicationContext(), "first", Toast.LENGTH_LONG).show();
                                firebaseAuthWithGoogle(account);
                            } catch (ApiException e) {
                                // Google Sign In failed, update UI appropriately
                                Toast.makeText(getApplicationContext(), "Google sign in Failed", Toast.LENGTH_LONG).show();
                            }
                        }
                    }
                });
        configSignIn();
        initAuth();
    }

    private void configSignIn(){
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
    }

    private void initAuth(){
        mAuth = FirebaseAuth.getInstance();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (isUserNonNull()){
            updateUI();
        }
    }

    private boolean isUserNonNull(){
        if (mAuth.getCurrentUser()==null){
            return false;
        } else {
            return true;
        }
    }

    private void updateUI(){

    }

    private void signIn() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        activityResultLauncher.launch(signInIntent);
    }


    // [START auth_with_google]
    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        // [START_EXCLUDE silent]
        // [END_EXCLUDE]

        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
                            FirebaseUser user = mAuth.getCurrentUser();
                            //updateUI(user);
                            Toast.makeText(getApplicationContext(), "Complete", Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(getApplicationContext(), MapActivity.class);
                            startActivity(intent);


                        } else {
                            // If sign in fails, display a message to the user.
                            // Snackbar.make(findViewById(R.id.main_layout), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
                            Toast.makeText(getApplicationContext(), "Authentication Failed", Toast.LENGTH_LONG).show();

                            // updateUI(null);
                        }

                        // [START_EXCLUDE]
                        // hideProgressDialog();
                        // [END_EXCLUDE]
                    }
                });
    }
    
    // [END auth_with_google]
    private void signOut() {
        // Firebase sign out
        mAuth.signOut();

        // Google sign out
        mGoogleSignInClient.signOut().addOnCompleteListener(this,
                new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        Toast.makeText(getApplicationContext(), "Complete", Toast.LENGTH_LONG).show();
                    }
                });
    }

    private void revokeAccess() {
        // Firebase sign out
        mAuth.signOut();

        // Google revoke access
        mGoogleSignInClient.revokeAccess().addOnCompleteListener(this,
                new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        Toast.makeText(getApplicationContext(), "Complete", Toast.LENGTH_LONG).show();
                    }
                });
    }


}

 

 

 

 

5. 로그인 성공시 화면 

firebase 구글 로그인 성공 이미지

'Android > Firebase' 카테고리의 다른 글

[Firebase] Android 프로젝트 연동하기  (0) 2022.12.25
Contents

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

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