Firebase認証実装
Firebaseのメール認証を実装するための説明です。基本はfirebaseのプロジェクトを作成する際に下記説明の内容は設定、表示されますので本説明ではサンプルに留めます。
必要情報
sign-in用のドメイン
利用可能ユーザの登録
認証ユーザはfirebaseのサイトのAuthentication >> Usersタブのユーザ追加で行います。
ログインページ
ログイン画面を実装する際のサンプルです。
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp, FirebaseError } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-analytics.js";
import { getAuth, signInWithEmailAndPassword, signInWithRedirect, signOut, setPersistence, browserSessionPersistence} from "https://www.gstatic.com/firebasejs/9.6.10/firebase-auth.js";
// 下記情報はfirebase環境毎に変更となります。
// 設定ファイル等で変更できるようご配慮ください。
const firebaseConfig = {
apiKey: "AIzaSyDYroJ8q2idftXRolz7cpCLu7B_gH7-UPQ",
authDomain: "farmnote-gene-dev.firebaseapp.com",
projectId: "farmnote-gene-dev",
storageBucket: "farmnote-gene-dev.appspot.com",
messagingSenderId: "328460512738",
appId: "1:328460512738:web:0e4872344372464fa31dbb",
measurementId: "G-V4HTQ1Q3V2"
};
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const auth = getAuth();
await signOut(auth); // ログアウト状態にする
// ログイン用関数
const signIn = async() => {
try{
const email = document.getElementById("userMail").value;
const password = document.getElementById("userPasswd").value;
await setPersistence(auth, browserSessionPersistence); // 認証の永続性設定(https://firebase.google.com/docs/auth/web/auth-state-persistence?hl=ja)
const userCredential = await signInWithEmailAndPassword(auth, email, password);
// ログイン成功
const user = userCredential.user;
console.log(user);
window.location.href="./authenticated_page.html"
}catch (err){
// ログイン失敗
console.log(err.message);
}
}
window.signIn = signIn;
</script>
ログアウトページ
ログアウト画面を実装する際のサンプルです。
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-analytics.js";
import { getAuth, signInWithEmailAndPassword, signInWithRedirect, signOut, setPersistence, browserSessionPersistence} from "https://www.gstatic.com/firebasejs/9.6.10/firebase-auth.js";
// 下記情報はfirebase環境毎に変更が必要です。
// 設定ファイル等で変更できるようご配慮ください。
const firebaseConfig = {
apiKey: "AIzaSyDYroJ8q2idftXRolz7cpCLu7B_gH7-UPQ",
authDomain: "farmnote-gene-dev.firebaseapp.com",
projectId: "farmnote-gene-dev",
storageBucket: "farmnote-gene-dev.appspot.com",
messagingSenderId: "328460512738",
appId: "1:328460512738:web:0e4872344372464fa31dbb",
measurementId: "G-V4HTQ1Q3V2"
};
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const auth = getAuth();
auth.onAuthStateChanged(function(user) {
if (user) {
signOut(auth).then(() => {
}).catch((error) => {
console.log(error)
});
}
});
</script>
アプリ側の実装例
認証が必要なページにすべて次の内容を実装してください。
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-analytics.js";
import { getAuth, signInWithEmailAndPassword, signInWithRedirect, signOut, setPersistence, browserSessionPersistence} from "https://www.gstatic.com/firebasejs/9.6.10/firebase-auth.js";
// 下記情報はfirebase環境毎に変更となります。
// 設定ファイル等で変更できるようご配慮ください。
const firebaseConfig = {
apiKey: "AIzaSyDYroJ8q2idftXRolz7cpCLu7B_gH7-UPQ",
authDomain: "farmnote-gene-dev.firebaseapp.com",
projectId: "farmnote-gene-dev",
storageBucket: "farmnote-gene-dev.appspot.com",
messagingSenderId: "328460512738",
appId: "1:328460512738:web:0e4872344372464fa31dbb",
measurementId: "G-V4HTQ1Q3V2"
};
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const auth = getAuth();
// ======================================
// ログイン済み確認
// ======================================
let idToken = null
auth.onAuthStateChanged(function(user) {
if (user) { // ログイン済みであることを確認
console.log(user.email); // メールアドレス(必要であれば取得)
console.log("Firebase UserID : " + user.uid);
// API認証で使用するIdTokenを取得
auth.currentUser.getIdToken(/* forceRefresh */ true).then(function(token) {
idToken = token // 取得したidTokenは1時間で期限切れとなります。
}).catch(function(error) {
// idToken取得エラー処理
alert("itToken取得エラー")
console.log(error)
window.location.reload(); // 再表示
});
// ログイン済みなので画面表示ON
const allview = document.getElementById("allview");
if(allview !== null) {
document.getElementById('allview').style.visibility = 'visible';
}
} else { // 未ログイン
console.log("not logged in");
// ログイン画面に移動
window.location.href ='./login.html';
}
});
</script>
(snip)
<div style="visibility: hidden;" id="allview">
認証OKであれば表示される内容
<a href="logout.html">ログアウト</a>
</div>