Search code examples
javascripthtmlwebfirebase-authenticationfirebaseui

FirebaseUi-Auth mandatory login


I am trying to implement mandatory login for my website. The problem I am having is that I can't find a way to do so. Let's say I create a SignIn page like...

  var uiConfig = {
    signInSuccessUrl: '<url-to-redirect-to-on-success>',
    signInOptions: [

      firebase.auth.GoogleAuthProvider.PROVIDER_ID,
      firebase.auth.FacebookAuthProvider.PROVIDER_ID,
      firebase.auth.TwitterAuthProvider.PROVIDER_ID,
      firebase.auth.GithubAuthProvider.PROVIDER_ID,
      firebase.auth.EmailAuthProvider.PROVIDER_ID,
      firebase.auth.PhoneAuthProvider.PROVIDER_ID
    ],

    tosUrl: '<your-tos-url>'
  };


  var ui = new firebaseui.auth.AuthUI(firebase.auth());

  ui.start('#firebaseui-auth-container', uiConfig);
</script>

..on a page called www.example.com/SignIn

If I go to www.example.com/Index

I could totally bypass all the signin.

I figured that something like this

 if ( FirebaseUser.getCurrentUser () != null ) {

redirect to sign in page }

How ?

Thanks


Solution

  • Use onAuthStateChanged listener on the www.example.com/Index page:

    firebase.auth().onAuthStateChanged(function(user) {
      if (!user) {
        window.location.assign('www.example.com/SignIn');
      }
      ...
    });
    

    However, this is not the right way to enforce access control. You should enforce signed in access via either mechanism:

    1. Firebase security rules (where you can have only authenticated users to access certain resources).
    2. By passing the ID token to your backend and verifying it using the Firebase Admin SDK before returning the restricted resource.

    Also you can use session cookies to do so, depending on your site architecture. Firebase now, also provides the ability to mint longer term session cookies