title: Firebase session expiration
body: <p>It looks like Firebase, when they moved from the v2 to v3.x SDKs (and now into v4), decided to remove the option for automatic session expiration in favor of the always-authenticated model.</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/37487283/firebase-3-x-token-session-expiration">Firebase 3.x - Token / Session Expiration</a></li>
  <li><a href="https://groups.google.com/forum/#!topic/firebase-talk/uYMlQny1Jb4" rel="noreferrer">https://groups.google.com/forum/#!topic/firebase-talk/uYMlQny1Jb4</a>  </li>
  </ul>
  
  <p>This is a nice feature to offer, but from a cybersecurity perspective, I see some problems as this is the <strong>only</strong> option for the Firebase SDKs with Firebase-generated tokens such as <a href="https://firebase.google.com/docs/reference/js/firebase.auth.Auth#signInWithEmailAndPassword" rel="noreferrer">email and password authentication</a> (some of which are explained well in the linked google group discussion). </p>
  
  <p>The commonly-provided suggestion to call <code>user.signOut()</code> on page exit has some holes. Namely, if the client crashes, then this code is never executed and therefore the strategy falls apart. The "sign out on page load" suggestion also has holes in it:</p>
  
  <ol>
  <li>Forces all users to log in every time the page loads/reloads (not the goal)</li>
  <li>As Firebase pushes most everything to the client, there is nothing stopping someone for creating a script that attempts to access a targeted Firebase <em>without</em> having the <code>user.signOut()</code></li>
  </ol>
  
  <p>I'm looking for a strategy that does a better job, from a cybersecurity perspective, that allows a user to opt in to the "always-authenticated" strategy if he/she so chooses, rather than it being the default (i.e. with a "Remember Me" button).</p>
  
  <p>One strategy I came up with is as follows:</p>
  
  <ol>
  <li>User signs in</li>
  <li>Get the generated JWT for that session and write it to Firebase</li>
  <li>If the user didn't select "remember me" on sign in, set up an <a href="https://firebase.google.com/docs/reference/js/firebase.database.OnDisconnect" rel="noreferrer">onDisconnect</a> handler that clears the token from the list of that users tokens</li>
  <li>In Firebase security rules, ensure that the JWT for the user making the request is in the list of tokens for that user</li>
  </ol>
  
  <p>This feels more secure because the <code>onDisconnect</code> method will still execute even if the browser crashes. <strong>But</strong>, the JWT is not available as a Firebase rules variable (<a href="https://firebase.google.com/docs/reference/security/database/#auth" rel="noreferrer">only the contents of the token</a>)!</p>
  
  <p>In light of these issues/flawed approaches, how can I invalidate a session after the browser closes/crashes (or even after a pre-determined period of time) with a Firebase-generated token?</p>