본문으로 바로가기

1.

모듈 app gradle에 인증에 대한 항목을 추가해준다.

현재 최신 버전은 11.2.0이다.

compile 'com.google.firebase:firebase-auth:10.0.1'
compile 'com.google.android.gms:play-services-auth:10.0.1'


2.

로그인을 시도 할 엑티비티에서 유저 데이터를 요청한다.

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();


3.

버튼 생성 SignInButton 이라고 구글에서 지원하는 버튼이 있다. 물론 커스텀 버튼 사용해도 됨.


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<com.google.android.gms.common.SignInButton
android:id="@+id/google_login_button"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginBottom="122dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"></com.google.android.gms.common.SignInButton>


</RelativeLayout>



4.

버튼 리스너 설정


signInButton = (SignInButton)findViewById(R.id.google_login_button);

signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
});


5.

로그인 Result를 받을 메서드. onActivityResult에서 정보를 받고 firebaseAuthWithGoogle에서 인증한다. 인증이 성공하면 메인엑티비티로 넘어간다.

@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) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();

Log.d(TAG, "이름 =" + account.getDisplayName());
Log.d(TAG, "이메일=" + account.getEmail());
Log.d(TAG, "getId()=" + account.getId());
Log.d(TAG, "getAccount()=" + account.getAccount());
Log.d(TAG, "getIdToken()=" + account.getIdToken());
firebaseAuthWithGoogle(account);
} else {
// Google Sign In failed, update UI appropriately
// ...
}
}
}


private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

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
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
Log.d(TAG, "signInWithCredential:success");
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}

// ...
}
});
}




항상 로그인 화면이 아닐테니까, 로그인 후 앱 사용 할 시에는 로그인 뷰를 보여주지 않는다.

public void onStart() { // 사용자가 현재 로그인되어 있는지 확인
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser!=null){ // 만약 로그인이 되어있으면 다음 액티비티 실행
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
}


전체코드 

접기

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;

import static android.content.ContentValues.TAG;

/**
* Created by user on 2017-11-04.
*/

public class LoginActivity extends AppCompatActivity {
final int RC_SIGN_IN = 1001; // 로그인 확인여부 코드
private FirebaseAuth mAuth;
private SignInButton signInButton; //구글 로그인 버튼
private GoogleApiClient mGoogleApiClient; //API 클라이언트
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);

mAuth = FirebaseAuth.getInstance(); // 인스턴스 생성

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();

mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();

signInButton = (SignInButton)findViewById(R.id.google_login_button);

signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
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) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();

Log.d(TAG, "이름 =" + account.getDisplayName());
Log.d(TAG, "이메일=" + account.getEmail());
Log.d(TAG, "getId()=" + account.getId());
Log.d(TAG, "getAccount()=" + account.getAccount());
Log.d(TAG, "getIdToken()=" + account.getIdToken());
firebaseAuthWithGoogle(account);
} else {
// Google Sign In failed, update UI appropriately
// ...
}
}
}

public void onStart() { // 사용자가 현재 로그인되어 있는지 확인
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser!=null){ // 만약 로그인이 되어있으면 다음 액티비티 실행
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

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
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
Log.d(TAG, "signInWithCredential:success");
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}

// ...
}
});
}

}

접기


참고 : https://firebase.google.com/docs/auth/android/google-signin?authuser=0

원문출처 : http://cres-cent.tistory.com/8


참고

http://dailyddubby.blogspot.com/2018/03/13-firebase-google.html

http://charactermail.tistory.com/98

http://superwony.tistory.com/2