------------------------------------------------------------------------구현성공-------------------------------------------------------------------
구글계정으로 로그인성공.
로그인 정보확인.
------------------------------------------------------------------------따라해보기-------------------------------------------------------------------
맨우측 상단에 '문서로 이동' 클릭
!!잠깐!! 왼쪽 메뉴 내용 설명
Authentication : 인증할 수 있는 부분
Database : 말그대로 DB
Storage : 사진 등 저장
Hosting : 파이어베이스 닷컴 기반으로 주소를 제공해주는것
Function : 자바스크립트로 코드를 짤수있다.(Node.js처럼)
Test Lab : 디바이스 테스트
Crush Reporting : 얼마나 충돌되는지 보는것
Performance : 성능에 대한 퍼포먼스 정보
Notification : Push보내고
Remote Config : 원격으로 정보조작
그 다음 'Android 시작하기' 클릭
그 다음 왼쪽 메뉴에서 'Google 로그인' 클릭 후 진행하자.
처음 순서는 Gradle에 파이어베이스를 컴파일.
그다음 부터는 공식홈페이지의 가이드를 참고해보자!!
------------------------------------------------------------------------가이드 시작-------------------------------------------------------------------
(참고 : https://firebase.google.com/docs/auth/android/google-signin?authuser=0)
앱에 Google 로그인을 통합하여 사용자가 Google 계정을 통해 Firebase에 인증하도록 할 수 있습니다.
시작하기 전에
- Android 프로젝트에 Firebase를 추가합니다.
- 앱 수준
build.gradle
파일에 Firebase 인증에 대한 종속 항목을 추가합니다.compile 'com.google.firebase:firebase-auth:11.2.0' compile 'com.google.android.gms:play-services-auth:11.2.0'
- 아직 Firebase 프로젝트에 앱을 연결하지 않았다면 Firebase 콘솔에서 연결합니다.
- 아직 앱의 SHA-1 지문을 지정하지 않았다면 Firebase 콘솔의 설정 페이지에서 지정합니다. 앱의 SHA-1 지문을 얻는 방법을 자세히 알아보려면 클라이언트 인증을 참조하세요.
- Firebase 콘솔에서 Google 로그인을 사용 설정합니다.
- Firebase 콘솔에서 인증 섹션을 엽니다.
- 로그인 방법 탭에서 Google 로그인 방법을 사용 설정하고 저장을 클릭합니다.
Firebase로 인증하기
- Android 앱에 Google 로그인 통합하기 페이지를 참고해 Google 로그인을 앱에 통합합니다. 다음과 같이
GoogleSignInOptions
개체를 구성할 때requestIdToken
을 호출합니다.// Configure Google Sign In
서버의 클라이언트 ID를
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();requestIdToken
메소드에 전달해야 합니다. OAuth 2.0 클라이언트 ID를 확인하는 방법은 다음과 같습니다.- API 콘솔에서 사용자 인증 정보 페이지를 엽니다.
- 웹 애플리케이션 유형의 클라이언트 ID가 백엔드 서버의 OAuth 2.0 클라이언트 ID입니다.
private void signIn() {
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();
firebaseAuthWithGoogle(account);
} else {
// Google Sign In failed, update UI appropriately
// ...
}
}
} - 다음과 같이 로그인 작업의
onCreate
메소드에서FirebaseAuth
개체의 공유 인스턴스를 가져옵니다.private FirebaseAuth mAuth;
// ...
mAuth = FirebaseAuth.getInstance(); - 활동을 초기화할 때 사용자가 현재 로그인되어 있는지 확인합니다.
@Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
} - 사용자가 정상적으로 로그인한 후에
GoogleSignInAccount
개체에서 ID 토큰을 가져와서 Firebase 사용자 인증 정보로 교환하고 Firebase 사용자 인증 정보를 사용해 Firebase에 인증합니다.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
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(GoogleSignInActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
// ...
}
});
}signInWithCredential
에 대한 호출이 성공하면getCurrentUser
메소드로 사용자의 계정 데이터를 가져올 수 있습니다.
다음 단계
사용자가 처음으로 로그인하면 신규 사용자 계정이 생성되고 사용자 인증 정보(사용자가 로그인할 때 사용한 사용자 이름과 비밀번호, 전화번호 또는 인증 제공업체 정보)에 연결됩니다. 이 신규 계정은 Firebase 프로젝트에 저장되며 사용자의 로그인 방법과 무관하게 프로젝트 내의 모든 앱에서 사용자 본인 확인에 사용할 수 있습니다.
앱에서
FirebaseUser
개체로부터 사용자의 기본 프로필 정보를 가져올 수 있습니다. 사용자 관리를 참조하세요.Firebase 실시간 데이터베이스와 Cloud Storage 보안 규칙에서
auth
변수로부터 로그인한 사용자의 고유 사용자 ID를 가져온 후 이 ID를 사용해 사용자의 데이터 액세스를 관리할 수 있습니다.
인증 제공업체의 사용자 인증 정보를 기존 사용자 계정에 연결하면 사용자들이 여러 인증 제공업체를 통해 앱에 로그인할 수 있습니다.
사용자를 로그아웃시키려면 signOut
을 호출합니다.
FirebaseAuth.getInstance().signOut();
------------------------------------------------------------------------완성 소스-------------------------------------------------------------------
java.
package com.namkit.namki.snslogin_function;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
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.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;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener{
private static final int RC_SIGN_IN = 10;
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();//싱글톤 패턴으로 작동이된다 '이해안감'
// Configure Google Sign In
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, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
//구글로그인 버튼에 대한 이벤트
SignInButton button = (SignInButton)findViewById(R.id.login_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("클릭테스트");
//이벤트 발생했을때, 구글로그인 버튼에 대한 (구글정보를 인텐트로 넘기는 값)
//"방금 로그인한다고 하는사람이 구글 사용자니? "물어보는로직
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
});
}
//Intent Result값 반환되는 로직
@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();
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
//Log.d(TAG, "signInWithCredential:success");
// FirebaseUser user = mAuth.getCurrentUser();
// updateUI(user);
Toast.makeText(MainActivity.this, "아이디 생성완료", Toast.LENGTH_SHORT).show();
} else {
// If sign in fails, display a message to the user.
//Log.w(TAG, "signInWithCredential:failure", task.getException());
// Toast.makeText(GoogleSignInActivity.this, "Authentication failed.",
// Toast.LENGTH_SHORT).show();
// updateUI(null);
}
// ...
}
});
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context="com.namkit.namki.snslogin_function.MainActivity">
<com.google.android.gms.common.SignInButton
android:id="@+id/login_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
안드로이드 FireBase 강의 Auth #1 - Google Login
(참고 : https://www.youtube.com/watch?v=u1CE6UtLbmQ&t=124s)
'프로그램언어+ > Android' 카테고리의 다른 글
OAuth 2.0과 네이버로 로그인 (0) | 2018.12.24 |
---|---|
Android에서 API를 이용한 로그인 로직을 응용해보자 (0) | 2018.05.23 |
안드로이드스튜디오에 Firebase 추가하기 (0) | 2018.05.22 |
Android SHA1 키 구하기(구글API로 SNS로그인 구현) (0) | 2018.05.22 |