5

How do i get currentUser in firebase admin SDK. In client SDK we can use

onAuthStateChanged() or firebase.auth().currentUser()

In NodeJs Server.js file firebase admin SDK onAuthStateChanged() Do not work, what should work here?

Basically i want only logged in users to access my innerPages so i am using express,nodejs app.get method to create routes.

app.get('/', authenticationRequired ,function(req,res){
    res.sendFile(path.join(__dirname+'/index.html'));
});

And trying to write authenticationRequired method (returns false or true depending on if user is logged in).

3
  • firebase.google.com/docs/auth/admin/verify-id-tokens Commented Jul 20, 2017 at 12:44
  • I have tried to getToken by firebase.auth().getToken() this error come up Cannot read property 'getToken' of undefined Commented Jul 20, 2017 at 13:07
  • firebase.auth().currentUser.getToken Commented Jul 20, 2017 at 13:29

1 Answer 1

25

The Firebase Admin SDK does not inherently know what user is using your Express web app. You will need to implement code for this. If you're already using Firebase Authentication in the web app, this takes these steps:

  1. Retrieve the user's ID token on the client

    You can get a user's ID token by using the firebase.auth().currentUser.getIdToken() method.

  2. Pass this token from the client to the server

  3. Verify the token on the server

    The user ID token can be verified using the admin.auth().verifyIdToken(idToken) method. On success it will return a promise with the decodedToken, otherwise it will return a rejected promise.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks - this approach makes sense. Any advice for cases where we use rewrites in the firebase.json file to serve content directly from a cloud function? i.e. we don't show users a static page in which I can do the above.
Thanks for your answer.. still valid in 2019 with a minor change in a method name. In step 1 the method getToken has been renamed to getIdToken: firebase.auth().currentUser.getIdToken()
FYI, this article has code complete version of this fireship.io/snippets/express-middleware-auth-token-firebase

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.