본문 바로가기
Front-end/Android (안드로이드 앱 개발)

Android studio , Firebase 파이어베이스 Google Login 구글 로그인

by javapp 자바앱 2021. 1. 1.
728x90

파이어베이스 인증

 

 

https://youtu.be/8sGY55yxicA

파이어베이스 인증은 다양한 로그인 방법을 제공한다.

이메일/비밀번호, 전화, 구글, play 게임, Facebook, Twitter, GitHub . . 

 

 

https://youtu.be/8sGY55yxicA

파이어베이스 인증은 새로운 계정을 생성하면 고유 ID 를 가지고 관리한다.

 


1.

모듈(앱 수준) Gradle 파일에

Firebase 인증 Android 라이브러리의 종속 항목을 선언한다.

dependencies {
    // Import the BoM for the Firebase platform
    implementation platform('com.google.firebase:firebase-bom:26.1.0')

    // Declare 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 declare the dependency for the Google Play services library and specify its version
    implementation 'com.google.android.gms:play-services-auth:19.0.0'
}

 

2.

싱글톤으로 FirebaseAuth 객체의 공유 인스턴스를 가져온다.

private FirebaseAuth mAuth;

        // Initialize Firebase Auth
        mAuth = FirebaseAuth.getInstance();

 

3.

앱 초기화시 현재 로그인 상태인지 확인

    //현재 로그인 상태인지 확인
    @Override
    public void onStart() {
        super.onStart();
        // Check if user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = mAuth.getCurrentUser();
        updateUI(currentUser);
    }

 


이메일 계정 생성

    //이메일 계정 생성
    private void createEmailUser(String email, String password)
    {
        mAuth.createUserWithEmailAndPassword(email, password)
                .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();

                            if(user != null)
                            {
                                Intent intent = new Intent(getApplication(), UserActivity.class);
                                startActivity(intent);
                            }

                            updateUI(user);
                        } else {
                            // If sign in fails, display a message to the user.
                            Toast.makeText(MainActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                            updateUI(null);
                        }

                        // ...
                    }
                });
    }

 

이메일 계정으로 로그인

    //이메일 로그인
    private void loginEmailUser(String email, String password)
    {
        mAuth.signInWithEmailAndPassword(email, password)
                .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();

                            if(user != null)
                            {
                                Intent intent = new Intent(getApplication(), UserActivity.class);
                                startActivity(intent);
                                finish();//자기자신 사라짐
                            }

                            updateUI(user);
                        } else {
                            // If sign in fails, display a message to the user.
                            Toast.makeText(MainActivity.this, "Authentication login failed.",
                                    Toast.LENGTH_SHORT).show();
                            updateUI(null);
                            // ...
                        }

                        // ...
                    }
                });
    }

 


 

구글 로그인

초기화시 구글 로그인을 앱에 통합한다.

서버 클라이언트 id 를 requestIdToken 메서드에 전달한다.

 

        // [START config_signin]
        // Configure Google Sign In
        /*==================구글 로그인을 앱에 통합 한다 =======================*/
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        // [END config_signin]

 

       googleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "클릭", Toast.LENGTH_SHORT).show();
                //로그인 통합 페이지 넘김
                Intent signInIntent = mGoogleSignInClient.getSignInIntent();
                startActivityForResult(signInIntent, RC_SIGN_IN);
            }
        });

 

 

    //구글을 통해 돌아온다.
    @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.getIdToken());
            } catch (ApiException e) {
                // Google Sign In failed, update UI appropriately
                // ...
            }
        }
    }

    //사용자가 정상적으로 로그인하면 GoogleSignInAccount 객체에서 ID토큰 가져와서
    //Firebase 사용자 인증 정보로 교환하고 해당 정보를 사용해 Firebase 인증
    private void firebaseAuthWithGoogle(String idToken)
    {
        AuthCredential credential = GoogleAuthProvider.getCredential(idToken, 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 firebaseUser = mAuth.getCurrentUser();

                            if(firebaseUser != null)
                            {
                                Intent intent = new Intent(getApplication(), UserActivity.class);
                                startActivity(intent);
                            }

                            updateUI(firebaseUser);
                            Toast.makeText(MainActivity.this, "성공", Toast.LENGTH_SHORT).show();
                        } else {
                            // If sign in fails, display a message to the user.
                            Toast.makeText(MainActivity.this, "실패", Toast.LENGTH_SHORT).show();

                            updateUI(null);
                        }

                    }
                });
    }

 


 

댓글