简体   繁体   中英

How to allow only authenticated users to access a certain page via backend

I am liking firebase and what it offers for app development, still learning it..

So I was wondering how could I allow certain pages to be only accessible authenticated users via cloud funtions?

I know I can do it in the client side which is easy by putting this code just at the top of your main script

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    //do something
  } else {
   // redirect to login page
  }
});

It works fine, but what about on the backend?

I have tried it this way -- index.js for the cloud functions.

const functions = require('firebase-functions');
const firebase = require('firebase');

  const config = {
    // needed configs here 

  };
  firebase.initializeApp(config);

exports.api = functions.https.onRequest((req, res) => {

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    res.status(200).send("logged in")
  } else {
    res.status(200).send("not logged in")
  }
});

});

So I have configured the rewrite rules like this

{
  "database": {
    "rules": "database.rules.json"
  },
  "hosting": {
    "public": "public",
    "rewrites": [ {
      "source": "/getstarted", "function": "api"
    } ]
  }
}

When I access /getstarted page it will check if authenticated if not just send unauthorized text / redirect to them /login page

So in my case after logging in the frontend, and I try to access /getstarted page it will still show not logged in

I must be doing something wrong..

Firebase cloud code runs on a remote server, not the clients web browser. The firebase variable in your cloud code has admin privileges by default, but will not be logged in as the same user as the client that makes a request to that piece of cloud code.

Also, onAuthStateChanged is an asynchronous function, that in practice will often return a null value on page load, quickly followed by returning an actual user once the page realizes a user was logged in. Because of its asynchronous nature, it is not fit for a single time (synchronous) check of if a user is logged in.

Instead, your first example with an asynchronous action on the client side is a good solution. It can result in "flashing" of a users only one to your clients, but that can be eliminated in many ways. One example would be to initially display a loading screen, and then to code

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // remove div containing loading screen
  } else {
    // redirect to login page 
  }
});

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