brunch

Firebase #06-2

Authentication

by 이승현

Federated identity provider integration



Authenticate users by integrating with federated identity providers. The Firebase Authentication SDK provides methods that allow users to sign in with their Google, Facebook, Twitter, and GitHub accounts.

(통합 로그인을 지원해주는 연합과 통합하여 사용자를 인증합니다. Firebase Authentication SDK는 구글, 페이스북, 트위터 그리고 깃허브 계정을 통한 로그인을 지원합니다.)


Google

Facebook

Twitter

GitHub




Authenticate Using Google Sign-In



https://firebase.google.com/docs/auth/android/google-signin

https://firebase.google.com/docs/reference/android/com/google/firebase/auth/GoogleAuthCredential

https://firebase.google.com/docs/reference/android/com/google/firebase/auth/GoogleAuthProvider


1. google-service.json 추가

#01 구성 파일 복사


2. plugin 추가

다운로드 (1).png #02 Project build.gradle에 추가
buildscript {
...
dependencies {
...
classpath 'com.google.gms:google-services:3.0.0'
}
}
11.PNG #03 app build.gradle에 추가
apply plugin: 'com.android.application'

...

dependencies {
...
compile 'com.google.firebase:firebase-auth:9.4.0'
compile 'com.google.android.gms:play-services-auth:9.4.0'
}

apply plugin: 'com.google.gms.google-services'


3. Enable Google sign-in in Firebase console


'Firebase Auth - 로그인 방법'에서 'Google'을 활성화합니다.

캡처11.PNG #04 Google 사용 설정
캡처12.PNG #05 Google 사용 설정

Android 앱의 Google 로그인을 설정하려면 프로젝트 설정에서 각 앱의 SHA-1 지문을 추가해야 합니다.

만약 추가해야 한다면 SHA-1은 아래 stackoverflow 방식대로 얻어서 입력합니다.

http://stackoverflow.com/questions/27609442/how-to-get-the-sha1-fingerprint-certificate-in-android-studio-for-debug-mode

추가한 후, 다시 google-services.json 파일을 받아 프로젝트에 추가합니다.

캡처13.PNG #06 SHA-1 추가


앱 클라이언트 ID와 보안 비밀은 Google API 콘솔에서 얻어옵니다.

캡처13.PNG #07 Google API 콘솔 클릭
캡처14.PNG #08 Google API 콘솔
캡처15.PNG #09 클라이언트 ID, 보안 비밀


4. Create GoogleApiClient object



private final String WEB_CLIENT_ID = "928488830433-camll1e451a5i4a0vrart4aia0rq707i.apps.googleusercontent.com";

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(WEB_CLIENT_ID)
.requestEmail()
.build();

Context context = getContext();
mGoogleApiClient = new GoogleApiClient.Builder(context)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
// fail
}
}).addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();


4. Sign in



private void signInWithGoogleSignIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, GOOGLE_SIGN_IN_REQUEST_CODE);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GOOGLE_SIGN_IN_REQUEST_CODE) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
mGoogleSignInTextView.setText("failed");
}
}
}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mFirebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(AuthenticationFragment.this.getActivity(), new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
String message;
if (task.isSuccessful()) {
// success
} else {
// fail
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
e.printStackTrace();
}
});
}


Sign in을 하면 아래와 같이 사용자에 추가됩니다.

캡처18.PNG #10 Google 계정


5. Sign out


private void signOut() {
if (mFirebaseAuth != null) {
mFirebaseAuth.signOut();
}
}




Authenticate Using Facebook Login



https://firebase.google.com/docs/auth/android/facebook-login

https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FacebookAuthCredential

https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FacebookAuthProvider


1. google-service.json 추가

#01 구성 파일 복사


2. plugin 추가

다운로드 (1).png #02 Project build.gradle에 추가
buildscript {
...
dependencies {
...
classpath 'com.google.gms:google-services:3.0.0'
}
}
캡처27.PNG #03 app build.gradle에 추가
apply plugin: 'com.android.application'

...

dependencies {
...
compile 'com.google.firebase:firebase-auth:9.4.0'
compile 'com.facebook.android:facebook-android-sdk:4.+'
}

apply plugin: 'com.google.gms.google-services'


3. Enable Facebook Login in Firebase console


'Firebase Auth - 로그인 방법'에서 'Facebook'을 활성화합니다.

캡처21.PNG #04 Facebook 사용 설정
#05 Facebook 사용 설정


4. Facebook for developers


Facebook 개발자 등록 후, 새 앱 추가를 합니다.

https://developers.facebook.com/

캡처23.PNG #06 Facebook 개발자 새 앱 추가
캡처24.PNG #07 앱 ID, 시크릿 코드 추가
캡처25.PNG #08 앱 공개 활성화
캡처26.PNG #09 유효한 OAuth 리디렉션 URI 등록


5. Facebook Login button


com.facebook.login.widget.LoginButton을 추가합니다.

<com.facebook.login.widget.LoginButton
android:id="@+id/facebook_login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />


6. Initialize Facebook SDK


onCreate에서 setContentView 이전에 sdk를 초기화합니다.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext()); // for facebook log in
setContentView(R.layout.activity_main);

initLayout();
}


7. Initialize Facebook login callback


private void initFBFacebookLogIn() {
mFacebookCallbackManager = CallbackManager.Factory.create();
mFacebookLoginButton.setFragment(this);
mFacebookLoginButton.setReadPermissions("email", "public_profile");
mFacebookLoginButton.registerCallback(mFacebookCallbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
mFaceBookLogInTextView.setText("onSuccess");
// success
}

@Override
public void onCancel() {
// cancel
}

@Override
public void onError(FacebookException error) {
// error
}

});
}


private void handleFacebookAccessToken(AccessToken token) {
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mFirebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(AuthenticationFragment.this.getActivity(), new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
String message;
if (task.isSuccessful()) {
// success
} else {
// fail
}
}
});
}

private final int FACEBOOK_LOG_IN_REQUEST_CODE = 64206;

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FACEBOOK_LOG_IN_REQUEST_CODE) {
mFacebookCallbackManager.onActivityResult(requestCode, resultCode, data);
}
}

Login을 하면 아래와 같이 사용자에 추가됩니다.

캡처20.PNG #10 Facebook 계정


8. Sign out


private void logOutWithFacebook() {
if (mFirebaseAuth != null) {
LoginManager.getInstance().logOut();
signOut();
}
}

private void signOut() {
if (mFirebaseAuth != null) {
mFirebaseAuth.signOut();
}
}





Authenticate Using Twitter



https://firebase.google.com/docs/auth/android/twitter-login

https://firebase.google.com/docs/reference/android/com/google/firebase/auth/TwitterAuthCredential

https://firebase.google.com/docs/reference/android/com/google/firebase/auth/TwitterAuthProvider


1. google-service.json 추가

#01 구성 파일 복사


2. plugin 추가

다운로드 (1).png #02 Project build.gradle에 추가
buildscript {
...
dependencies {
...
classpath 'com.google.gms:google-services:3.0.0'
}
}
캡처30.PNG #03 app build.gradle에 추가
apply plugin: 'com.android.application'

...

dependencies {
...
compile 'com.google.firebase:firebase-auth:9.4.0'
compile('com.twitter.sdk.android:twitter-core:1.7.0@aar') {
transitive = true;
}
compile('com.twitter.sdk.android:twitter:1.7.0@aar') {
transitive = true;
}
}

apply plugin: 'com.google.gms.google-services'


3. Enable Twitter Login in Firebase console


'Firebase Auth - 로그인 방법'에서 'Twitter'를 활성화합니다.

캡처31.PNG #04 Twitter 사용 설정
캡처32.PNG #05 Twitter 사용 설정


4. Twitter for developers


Twitter 개발자 등록 후, Create New App을 합니다.

https://apps.twitter.com/

캡처33.PNG #06 Create New App
캡처.PNG #07 Create an application
캡처2.PNG #08 New App
캡처3.PNG #09 Consumer Key, Secret 등록


5. Twitter Login button


com.twitter.sdk.android.core.identity.TwitterLoginButton을 추가합니다.

<com.twitter.sdk.android.core.identity.TwitterLoginButton
android:id="@+id/twitter_login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_centerInParent="true"/>


6. Initialize Twitter


tw1.PNG
private final String TWITTER_CONSUMER_KEY = "NDPH7edclsp7gK4GVPDPKwKGm";
private final String TWITTER_CONSUMER_SECRET = "Wjne0Ct1WLipHGdn1q2tX529xG3tEyss1RVFjl7dD9HY6e7z1m";

private void initFBTwitterLogIn() {
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET);
Fabric.with(AuthenticationFragment.this.getContext(), new Twitter(authConfig));
}


7. Initialize Twitter login callback


private void setTwitterLogInCallback() {
mTwitterLoginButton.setCallback(new Callback<TwitterSession>() {
@Override
public void success(Result<TwitterSession> result) {
// success
}

@Override
public void failure(TwitterException exception) {
// fail
}
});
}
private void handleTwitterSession(TwitterSession session) {
AuthCredential credential = TwitterAuthProvider.getCredential(
session.getAuthToken().token,
session.getAuthToken().secret);

mFirebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(AuthenticationFragment.this.getActivity(), new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
String message;
if (task.isSuccessful()) {
// success
} else {
// fail
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// error
}
});
}


Login을 하면 아래와 같이 사용자에 추가됩니다.

1111.PNG


8. Sign out


private void logOutWithTwitter() {
if (mFirebaseAuth != null) {
Twitter.logOut();
signOut();
}
}

private void signOut() {
if (mFirebaseAuth != null) {
mFirebaseAuth.signOut();
}
}




Authenticate Using GitHub



https://firebase.google.com/docs/auth/android/github-auth

https://firebase.google.com/docs/reference/android/com/google/firebase/auth/GithubAuthCredential

https://firebase.google.com/docs/reference/android/com/google/firebase/auth/GithubAuthProvider


1. google-service.json 추가

#01 구성 파일 복사


2. plugin 추가

다운로드 (1).png #02 Project build.gradle에 추가
buildscript {
...
dependencies {
...
classpath 'com.google.gms:google-services:3.0.0'
}
}
22222.PNG #03 app build.gradle에 추가
apply plugin: 'com.android.application'

...

dependencies {
...
compile 'com.google.firebase:firebase-auth:9.4.0'
}

apply plugin: 'com.google.gms.google-services'


3. Enable Github in Firebase console


'Firebase Auth - 로그인 방법'에서 'Github'을 활성화합니다.

22223.PNG #04 Github사용 설정
22224.PNG #05 Github사용 설정


4. Github


Github 가입 후, 새 앱 추가를 합니다.

https://github.com/settings/applications/new

캡처4.PNG #06 Register a new OAuth application
캡처5.PNG #07 Client ID, Secret
캡처6.PNG #08 Personal access tokens - Generate new tokens
캡처8.PNG #09 Generate new token
캡처7.PNG 10. new token



5. Initialize Github login


private final String GITHUB_TOKEN = "4dfd90fb0ac9ef75c4aabcc87ee0cdd4062a921c";

private void initFBGithubLogIn() {
AuthCredential credential = GithubAuthProvider.getCredential(GITHUB_TOKEN);
mFirebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(AuthenticationFragment.this.getActivity(), new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// success
} else {
// fail
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// fail
}
});
}



6. Sign out


private void signOut() {
if (mFirebaseAuth != null) {
mFirebaseAuth.signOut();
}
}




Sample


https://github.com/oemilk/firebase/tree/master/app/src/main/java/com/sh/firebase/authentication




keyword
작가의 이전글Firebase #06-1