Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect user who isn't logged in before the page loads

I have question regarding security of a website which im building with googles firebase. For now it is very simple website with registration/login form and possibility to log in. When the user logs in, he is redirected to another page:

  firebase.auth().onAuthStateChanged(firebaseUser => {
    if(firebaseUser){
      window.location = 'home.html';
    } else {
      console.log('not logged in');
    }
  });

Now as anyone can see the js file, you can tell where the user is going to be redirected without even having an account, so someone could just type in the website adress with /home.html at the end to bypass the login form. So in the home.html I added a script which will redirect user who isn't logged in back to the main page:

if(!firebaseUser){
  window.location = 'index.html';
} 

Which works fine for now, the user gets to the page but is redirected almost instantly if he isn't logged in. But I imagined a situation where I would have some private information on my webpage and I wouldn't want anyone else to be able to login. Yet, if someone would disable javascript in browser settings and type the adress with home.html he could access the page and not get redirected.

Question

Is there some solution for that situation? To somehow check if the user is logged in and redirect him if he's not before he gains access to the websites files?

like image 800
aMJay Avatar asked Jan 01 '26 05:01

aMJay


1 Answers

You can't enforce this client side. Anyone can just navigate to the logged in page. You have to enforce it on your backend or security rules. For example, let's say the logged in page displays the user's information, you will either be enforcing this via Firebase security rules (if you are using realtime database or Firestore, etc) or by sending the user's ID token to your server (if you are using your own backend database) and verifying it before returning content to be displayed. If someone is not logged in, they will get an error which you catch and redirect back to login page.

Another option, if you want to use session cookies and your own database is to try Firebase Auth's session cookie management solution.

like image 148
bojeil Avatar answered Jan 02 '26 17:01

bojeil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!