LoginSignup
75
55

More than 5 years have passed since last update.

FirebaseのGoogleアカウントOAuth認証を試したのでメモ

Last updated at Posted at 2016-09-24

サーバサイド実装しなくても手軽にOAuth認証やデータ保存ができるということで便利そうなのでためしてみた。

プロジェクトを作成する

スクリーンショット 2016-09-24 13.46.47.png

  • 「ウェブアプリに Firebase を追加」をクリックするとWebページに貼り付けるコードが表示される

スクリーンショット 2016-09-24 13.48.43.png

googleアカウントで認証できるように設定する

firebase-toolsを使う

  • npm install -g firebase-tools
  • firebase loginでgoogleアカウントでログインする
  • プロジェクト用のディレクトリを適当につくってfirebase initする

スクリーンショット 2016-09-24 13.55.40.png

  • いろいろ聞いてくるので以下のように回答
    • Hosting: Configure and deploy Firebase Hosting sites
    • [don't setup a default project]
    • その他はデフォルトどおり
  • 以下のようにファイルがつくられる

スクリーンショット 2016-09-24 13.57.11.png

スクリーンショット 2016-09-24 14.00.13.png

googleのOAuth認証を組み込む

  • public/index.htmlに「ウェブアプリに Firebase を追加」で表示される貼り付けコードを貼る
  • 以下のようなコードを書く
<button class="authBtn" disabled></button>
<span class="userId"></span>

<script>
var AuthUI = {
  init: function(){
    AuthUI.provider = new firebase.auth.GoogleAuthProvider();
    AuthUI.elAuthBtn = document.querySelector('.authBtn');
    AuthUI.elUserId = document.querySelector('.userId');
    AuthUI.draw();
    AuthUI.elAuthBtn.addEventListener('click', function(){
      AuthUI.doAuth();
    });
    firebase.auth().getRedirectResult().then(function(result) {
      AuthUI.elAuthBtn.disabled = false;
      if (result.credential) {
        // This gives you a Google Access Token. You can use it to access the Google API.
        var token = result.credential.accessToken;
      }
      if(result.user){
        AuthUI.data.authed = true;
        AuthUI.data.userId = result.user.email;
        AuthUI.draw();
      }
    }).catch(function(error) {
      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;
      // The email of the user's account used.
      var email = error.email;
      // The firebase.auth.AuthCredential type that was used.
      var credential = error.credential;
      // ...
    });
  },
  data: {
    authed: false,
    userId: '',
    info: ''
  },
  draw: function(){
    AuthUI.elAuthBtn.textContent = AuthUI.data.authed ? 'LOGOUT' : 'LOGIN';
    AuthUI.elUserId.textContent = AuthUI.data.userId;
  },
  doAuth: function(){
    if(AuthUI.data.authed){
      firebase.auth().signOut().then(function() {
        AuthUI.data.authed = false;
        AuthUI.data.userId = '';
        AuthUI.draw();
      }, function(error) {
        // An error happened.
      });
    }
    else {
      firebase.auth().signInWithRedirect(AuthUI.provider);
    }
  }
};
AuthUI.init();
</script>

以下のように動く

1回目のログイン
login.gif

2回目以降のログイン
login2.gif

Googleアカウントの接続許可は以下で管理
https://security.google.com/settings/security/permissions?utm_source=OGB&pli=1

で、これをこのままgh-pagesとかで動かそうとしてもエラーになるので、https://console.firebase.google.com/project/hoge-proj/authentication/providers にてOAuthリダイレクトドメインを設定する。

スクリーンショット 2016-09-24 15.40.30.png

Demo

75
55
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
75
55