Alex
Alex

Reputation: 57

how to authenticate with custom uid in firebase realtime database using javascript?

this is my realtime database

enter image description here

I use firebase realtime database, I use rules as below:

 {
  "rules": {
    "$uid": {
    ".read":"$uid === auth.uid",
    ".write": false
  }
}
}

when I use the playground rules as below it works, here I managed to read the 121212 data above.

enter image description here

This is my code snippet.

<script>
// Import the functions you need from the SDKs you need
    import {
        initializeApp
    } from "https://www.gstatic.com/firebasejs/9.6.11/firebase-app.js";
    import {
        getDatabase,
        ref,
        onValue,
    } from "https://www.gstatic.com/firebasejs/9.6.11/firebase-database.js";
    import {
        getAuth,
        signInWithCustomToken,
        createCustomToken
    } from "https://www.gstatic.com/firebasejs/9.6.11/firebase-auth.js";

    // TODO: Add SDKs for Firebase products that you want to use
    // https://firebase.google.com/docs/web/setup#available-libraries

    // Your web app's Firebase configuration
    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
    const firebaseConfig = {
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        projectId: "",
        storageBucket: "",
        messagingSenderId: "",
        appId: "",
        measurementId: ""
    };

    // Initialize Firebase
    const app = initializeApp(firebaseConfig);

</script>

The problem is, I want to read 121212 data via javascript.

Upvotes: 2

Views: 744

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

If you don't want the user to have to provide credentials, but still want then to only be able to access their own data, consider using Firebase's anonymous authentication where signing in is as easy as:

import { getAuth, signInAnonymously } from "firebase/auth";

const auth = getAuth();
await signInAnonymously(auth);

Upvotes: 0

Dharmaraj
Dharmaraj

Reputation: 50830

The auth.uid is UID of user logged in with Firebase Authentication in your web app requesting the data. First you'll have to sign them in:

import {
  getAuth,
  signInWithEmailAndPassword,
} from "https://www.gstatic.com/firebasejs/9.6.11/firebase-auth.js";

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

signInWithEmailAndPassword(auth, "[email protected]", "password").then((user) => {
  // read data using Firebase Realtime Database SDK
})

Firebase has recently posted many tutorials on their YouTube channel that would be useful:

Upvotes: 1

Related Questions