Is there any way to get Firebase Auth User UID?

121,275

Solution 1

Auth data is asynchronous in Firebase 3. So you need to wait for the event and then you have access to the current logged in user's UID. You won't be able to get the others. It will get called when the app opens too.

You can also render your app only once receiving the event if you prefer, to avoid extra logic in there to determine if the event has fired yet.

You could also trigger route changes from here based on the presence of user, this combined with a check before loading a route is a solid way to ensure only the right people are viewing publicOnly or privateOnly pages.

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // User logged in already or has just logged in.
    console.log(user.uid);
  } else {
    // User not logged in or has just logged out.
  }
});

Within your app you can either save this user object, or get the current user at any time with firebase.auth().currentUser.

https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onAuthStateChanged

Solution 2

if a user is logged in then the console.log will print out:

if (firebase.auth().currentUser !== null) 
        console.log("user id: " + firebase.auth().currentUser.uid);

Solution 3

on server side you can use firebase admin sdk to get all user information :

const admin = require('firebase-admin')
var serviceAccount = require("./serviceAccountKey.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://yourprojecturl.firebaseio.com",
});

admin.auth().listUsers().then(data=>{
    console.log(data.users)
})

Solution 4

This is an old question but I believe the accepted answer provides a correct answer to a different question; and although the answer from Dipanjan Panja seems to answer the original question, the original poster clarified later in a reply with a different question:

Basically, I need to generate token from UID by Firebase.auth().createCustomToken(UID) to sign in user on firebase with the following function firebase.auth().signInWithCustomToken(token).

Because the original question was clarified that the intent is to use createCustomToken and signInWithCustomToken, I believe this is a question about using the Firebase Admin SDK or Firebase Functions (both server-side) to provide custom authentication, probably based on a username and password combination, rather than using an email address and password.

I also think there's some confusion over "uid" here, where in the code example below, it does NOT refer to the user's Firebase uid, but rather the uid indicated in the doc for createCustomToken, which shows:

admin
  .auth()
  .createCustomToken(uid)
  .then((customToken) => {
    ...

In this case, the uid parameter on the createCustomToken call is not the Firebase uid field (which would not yet be known), thus providing a series of frustrating replies to the coder asking this question.

Instead, the uid here refers to any arbitrary basis for logging in for which this custom auth will support. (For example, it could also be an email address, social security number, employee number, anything...)

If you look above that short code block from the documentation page, you'll see that in this case uid was defined as:

const uid = 'some-uid';

Again, this could represent anything that the custom auth wanted it to be, but in this case, let's assume it's username/userid to be paired with a password. So it could have a value of 'admin' or 'appurist' or '123456' or something else.

Answer: So in this case, this particular uid (misnamed) is probably coming from user input, on a login form, which is why it is available at (before) login time. If you know who is trying to log in, some Admin SDK code code then search all users for a matching field (stored on new user registration).

It seems all of this is to get around the fact that Firebase does not support a signInWithUsernameAndPassword (arbitrary userid/username) or even a signInWithUidAndPassword (Firebase UID). So we need Admin SDK workarounds, or Firebase Functions, and the serverless aspect of Firebase is seriously weakened.

For a 6-minute video on the topic of custom auth tokens, I strongly recommend Jen Person's YouTube video for Firebase here: Minting Custom Tokens with the Admin SDK for Node.js - Firecasts

Solution 5

As of now in Firebase console, there is no direct API to get a list of users, Auth User(s) UID.
But inside your Firebase database, you can maintain the User UID at user level. As below,

"users": {
  "user-1": {
    "uid": "abcd..",
    ....
  },
  "user-2": {
    "uid": "abcd..",
    ....
  },
  "user-3": {
    "uid": "abcd..",
    ....
  }
}

Then you can make a query and retrieve it whenever you need uid's.
Hope this simple solution could help you!

Share:
121,275
Piyush Bansal
Author by

Piyush Bansal

Hi everyone, I am working as an Application Developer by profession and working with Lazy Gardener in New Delhi, India. I'm running my eCommerce business (sunshield.in) which is related to door fittings hardware products & home decor accessories. My interest areas are eCommerce, Digital Marketing, Photography, Programming. And I am eager to learn new things.

Updated on July 09, 2022

Comments

  • Piyush Bansal
    Piyush Bansal almost 2 years

    I am looking to fetch Auth User(s) UID from Firebase via NodeJS or Javascript API. I have attached screenshot for it so that you will have idea what I am looking for.

    enter image description here

    Hope, you guys help me out with this.

  • Piyush Bansal
    Piyush Bansal almost 8 years
    Basically, I need to generate token from UID by Firebase.auth().createCustomToken(UID) to sign in user on firebase with the following function firebase.auth().signInWithCustomToken(token). Is there any other way to Sign In User on firebase ?
  • Piyush Bansal
    Piyush Bansal almost 8 years
    If I try it, authdata.uid belongs to which user? the problem is that I need UID to signin user on firebase and without authentication, how can I get the correct UID.
  • Piyush Bansal
    Piyush Bansal almost 8 years
    But I need UID to login user.
  • Selfish
    Selfish almost 8 years
    I believe this belongs to the currently authenticated user, this can be easily confirmed against the DB..
  • Dominic
    Dominic almost 8 years
    I'm not sure what you mean, this will give you the UID of the logged in user. You can't get the UID of others.
  • Karthi R
    Karthi R almost 8 years
    Firebase makes authentication easy. It has built-in functionality for email & password, and third-party providers such as Facebook, Twitter, GitHub, and Google. And with Firebase custom Authentication API, you can integrate with your existing login server too.
  • Karthi R
    Karthi R almost 8 years
    For more info go through these articles, hope this would help you, Link-1 and Link-2
  • Piece Digital
    Piece Digital over 7 years
    This methods is not triggering at all for me.
  • Fractaly
    Fractaly about 5 years
    I was having an issue where this is not available immediately on page load. The callback method (onAuthStateChanged) worked for me though.
  • Admin
    Admin about 5 years
    This is not a solution to the problem
  • Appurist - Paul W
    Appurist - Paul W over 3 years
    @PiyushBansal The (mostly misnamed) "uid" is any value, in this case probably coming from the user input, e.g. a login form. It's not the Firebase user uid. So in this case it's probably the username that you want to login with. See my longer answer below.