e.iluf
e.iluf

Reputation: 1659

How to Send Firebase token from client side and receive it in server.js

I want to send the user token generated by firebase on client side to server. How do I do this?

I have been able to generate the token on the client side and attempted to POST it to server but I keep getting internal server error.

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

client side code

        firebase.auth().currentUser
            .getIdToken()
            .then(function (token) {
              console.log(token)
                accessToken = token;


            });

            var mydata = {
              customToken: accessToken
            }

             $.post('/auth',mydata, function(data, status){

                      console.log(data+" and status is "+ status)

             })

server.js code

app.post('/auth', function(req, res){

  var token = req.body

  res.render(token)



})

I want to be able to read the token in /auth. What am I doing wrongly?

Upvotes: 3

Views: 782

Answers (1)

Mauro Stepanoski
Mauro Stepanoski

Reputation: 725

You should put the request inside of then function:

firebase.auth().currentUser.getIdToken().then(function (token) {
   console.log(token)
   var mydata = {
     customToken: accessToken
   }

   /* $.post('/auth',mydata, function(data, status){
       console.log(data.token + " and status is " + status)
   }) */
   // https://stackoverflow.com/questions/16498256/posting-json-to-express-using-jquery
   // https://stackoverflow.com/questions/6323338/jquery-ajax-posting-json-to-webservice
   $.ajax({
      url: '/auth',
      type: 'POST',
      contentType: 'application/json',
      dataType: 'json',
      data: JSON.stringify(mydata),
      success: function (data) {
        console.log(data.token)
      },
      error: function(jqXHR, textStatus, errorThrown) { console.error(errorThrown) }
  })
})

Firebase getIdToken returns a Promise, so the code is async. Read more about it here: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Promise

The server should use firebase-admin package to verify token. Sample setup:

const admin = require('firebase-admin')
let serviceAccount = null

try {
  // download serviceAccount.json from Firebase
  serviceAccount = require('./serviceAccount.json')
  admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: FIREBASE_DB_PATH
  })
} catch (err) {
  console.error('An error has occurred configuring Firebase')
}

And remember to parse the JSON body request in express:

const bodyParser = require('body-parser')

...express config...

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

Then you can access the token:

app.post('/auth', async (req, res) => {
  /* if you are using node >= 10 use the line below,
     but use this: const token = req.body.customToken */
  const { customToken: token } = req.body
  let decodedToken = null
  // For example check token
  try { 
     decodedToken = await admin.auth().verifyIdToken(token)
  } catch (err) {
     console.error('Error trying to verify the token: ' + err)
     return res.status(403).json({ message: err.message })
  }

  return res.status(200).json({ token: decodedToken })
})

You should check this link https://medium.com/@yaniv_g/dont-use-bodyparser-json-with-jquery-post-d034c44ac7ad

Upvotes: 2

Related Questions