LoginSignup
15
9

More than 5 years have passed since last update.

Expo で Firebase Authentication で認証する

Last updated at Posted at 2018-02-20

前置き

expo を使う場合、認証周りが非常に面倒臭い印象だったが、 expo と firebase 周りが非常に整理されて使いやすい感じになっていた。

基本的に https://docs.expo.io/versions/latest/guides/using-firebase.html に書いてあるとおりにやるだけでFirebaseの認証が実装できる。

手順

  • developers.facebook.com/apps > 新しいアプリを登録 > APP_ID と secret_token をメモ
  • console.firebase.google.com > アプリを選択 > Authentication > Sign-in providers > Firebase > Enable にして APP_ID と secret_token を入力
import firebase from 'firebase'

// Firebase web 用の config
const config = {
  apiKey: '<api key>',
  authDomain: '<domain>',
  databaseURL: '<database url>',
  projectId: '<project id>',
  storageBucket: '<sotarge bucket>',
  messagingSenderId: '<id>'
}

firebase.initializeApp(config)

// 認証時のコールバック
firebase.auth().onAuthStateChanged(user => {
  if (user != null) {
    console.log('We are authenticated now!')
  }

  // Do other things
})


// このボタンを render

      <Button
        title="Start with Facebook Auth"
        onPress={async () => {
          const {
            type,
            token
          } = await Expo.Facebook.logInWithReadPermissionsAsync(
            '<Facebook APP ID>',
            {
              permissions: ['public_profile']
            }
          )

          if (type === 'success') {
            // Build Firebase credential with the Facebook access token.
            const credential = firebase.auth.FacebookAuthProvider.credential(
              token
            )

            // Sign in with credential from the Facebook user.
            firebase
              .auth()
              .signInWithCredential(credential)
              .catch(error => {
                console.error(error)
                // Handle Errors here.
              })
          }
        }}
      />

その他の認証

によると次のようなコードで行けるらしいと書いてあるが、試してはない。まあ雰囲気はわかる。

const googleAuthenticate = (token) => {
  const provider = firebase.auth.GoogleAuthProvider;
  provider.addScopes('profile');
  provider.addScopes('email');
  const credential = provider.credential(token);
  return firebase.auth().signInWithCredential(credential);
}; 

要は provider で認証させて token がとれたら provider.credential(token) の結果を firebase.auth().signInWithCredential(credential) すればいいっぽい

15
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
9