简体   繁体   中英

How do I make a protected webpage/panel with Firebase authentication?

I want to know if I can make a protected website which only people which are logged in via firebase authentication can access and use.

Yes you can. You just need to check if a user is logged in on page load.

import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    const uid = user.uid;
    // ...
  } else {
    // User is signed out
    // redirect to login
  }
});

If the user is not logged in, just redirect then. That was for user facing part. You should setup your security rules in such a way that only authenticated users can access your Firebase resources. I'm not totally sure which services you are using but let's take Firestore as an example:

match /collection/{docs=**} {
  allow read: if request.auth!= null;
}

This rules will allow only logged in users to read data from that collection. These were basic rules but you can write granular rules such a user specific content and much more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM