Authentication
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는 구글, 페이스북, 트위터 그리고 깃허브 계정을 통한 로그인을 지원합니다.)
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
buildscript {
...
dependencies {
...
classpath 'com.google.gms:google-services:3.0.0'
}
}
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'
'Firebase Auth - 로그인 방법'에서 'Google'을 활성화합니다.
Android 앱의 Google 로그인을 설정하려면 프로젝트 설정에서 각 앱의 SHA-1 지문을 추가해야 합니다.
만약 추가해야 한다면 SHA-1은 아래 stackoverflow 방식대로 얻어서 입력합니다.
추가한 후, 다시 google-services.json 파일을 받아 프로젝트에 추가합니다.
앱 클라이언트 ID와 보안 비밀은 Google API 콘솔에서 얻어옵니다.
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();
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을 하면 아래와 같이 사용자에 추가됩니다.
private void signOut() {
if (mFirebaseAuth != null) {
mFirebaseAuth.signOut();
}
}
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
buildscript {
...
dependencies {
...
classpath 'com.google.gms:google-services:3.0.0'
}
}
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'
'Firebase Auth - 로그인 방법'에서 'Facebook'을 활성화합니다.
Facebook 개발자 등록 후, 새 앱 추가를 합니다.
https://developers.facebook.com/
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" />
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();
}
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을 하면 아래와 같이 사용자에 추가됩니다.
private void logOutWithFacebook() {
if (mFirebaseAuth != null) {
LoginManager.getInstance().logOut();
signOut();
}
}
private void signOut() {
if (mFirebaseAuth != null) {
mFirebaseAuth.signOut();
}
}
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
buildscript {
...
dependencies {
...
classpath 'com.google.gms:google-services:3.0.0'
}
}
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'
'Firebase Auth - 로그인 방법'에서 'Twitter'를 활성화합니다.
Twitter 개발자 등록 후, Create New App을 합니다.
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"/>
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));
}
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을 하면 아래와 같이 사용자에 추가됩니다.
private void logOutWithTwitter() {
if (mFirebaseAuth != null) {
Twitter.logOut();
signOut();
}
}
private void signOut() {
if (mFirebaseAuth != null) {
mFirebaseAuth.signOut();
}
}
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
buildscript {
...
dependencies {
...
classpath 'com.google.gms:google-services:3.0.0'
}
}
apply plugin: 'com.android.application'
...
dependencies {
...
compile 'com.google.firebase:firebase-auth:9.4.0'
}
apply plugin: 'com.google.gms.google-services'
'Firebase Auth - 로그인 방법'에서 'Github'을 활성화합니다.
Github 가입 후, 새 앱 추가를 합니다.
https://github.com/settings/applications/new
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
}
});
}
private void signOut() {
if (mFirebaseAuth != null) {
mFirebaseAuth.signOut();
}
}
https://github.com/oemilk/firebase/tree/master/app/src/main/java/com/sh/firebase/authentication