简体   繁体   中英

How to get Twitter username from Firebase Authentication - Javascript

I'm using firebase twitter authentication for my project. The auth variable returning the credentials does not contain the account's twitter username but everything else.

I need to work with the username, is there a way to work around this? Users shown in the console look like this Firebase Console

How do I get the respective identifier of a uid?

import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.2/firebase-app.js";
import { getAuth, signInWithPopup, TwitterAuthProvider } from "https://www.gstatic.com/firebasejs/9.1.2/firebase-auth.js";

const app = initializeApp(firebaseConfig);
const provider = new TwitterAuthProvider();

const auth = getAuth();


document.querySelector('button').addEventListener('click', authenticate);

function authenticate() {
  signInWithPopup(auth, provider)
    .then((result) => {
  
      const credential = TwitterAuthProvider.credentialFromResult(result);
      const token = credential.accessToken;
      const secret = credential.secret;

      const user = result.user;
      console.log(result)
    }).catch((error) => {
      const errorCode = error.code;
      const errorMessage = error.message;
      const email = error.email;
      const credential = TwitterAuthProvider.credentialFromError(error);
      console.log(error);
    });
}

Is there a way to get the username from this 'auth' variable, check below code for ref

import { getAuth } from "https://www.gstatic.com/firebasejs/9.1.2/firebase-auth.js"

const auth = getAuth();
auth.onAuthStateChanged(user => {
  if(user){
    // window.location.href = "/home/index.html"
  }else{

  }
})

Hello there you can try this:

firebase.auth().signInWithPopup(new firebase.auth.TwitterAuthProvider())
  .then((userCredential) => {
    // here you get the username
    console.log(userCredential.additionalUserInfo.username);
  })
  .catch((error) => {
    console.log("error occurred");
  });

or else you can get the info using this if you are having id :

let url = `https://api.twitter.com/1.1/users/show.json?user_id=${the_uid_from_provider_data}`;
fetch(url)
    .then(response => {
        let data = response.json();
        console.log(data);
    })
    .catch(error => {
        // handle the error
    });

I think you mean Twitter handle (also called screen name) by "username"

 const provider = new TwitterAuthProvider();
 const userInfo = await signInWithPopup(auth, provider);
 console.log(userInfo._tokenResponse.screenName) // twitter handle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM