Skip to content

Instantly share code, notes, and snippets.

@filipelinhares
Last active June 9, 2023 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save filipelinhares/7a4ec753ae4e623ddfabdffc123abb43 to your computer and use it in GitHub Desktop.
Save filipelinhares/7a4ec753ae4e623ddfabdffc123abb43 to your computer and use it in GitHub Desktop.
Firebase Auth Middleware
'use strict'
require('firebase-functions/lib/logger/compat')
const functions = require('firebase-functions')
const admin = require('firebase-admin')
const express = require('express')
const cookieParser = require('cookie-parser')
const cors = require('cors')
try {
admin.initializeApp(functions.config().firebase)
} catch (e) {
// You do that because the admin SDK can only be initialized once.
}
const validateFirebaseIdToken = async (req, res, next) => {
if (
(!req.headers.authorization ||
!req.headers.authorization.startsWith('Bearer '))
) {
res.status(403).send('Unauthorized')
return
}
let idToken
if (
req.headers.authorization &&
req.headers.authorization.startsWith('Bearer ')
) {
idToken = req.headers.authorization.split('Bearer ')[1]
} else {
res.status(403).send('Unauthorized')
return
}
try {
const decodedIdToken = await admin.auth().verifyIdToken(idToken)
req.user = decodedIdToken
next()
return
} catch (error) {
res.status(403).send('Unauthorized')
return
}
}
const app = express()
app.use(
cors({
origin: [
/.*localhost:\d*/
],
credentials: true
})
)
app.use(cookieParser())
app.use(validateFirebaseIdToken)
app.post('/', async (req, res) => {
res.send({message: 'Hello' })
})
module.exports = functions.https.onRequest(app)
@BossBele
Copy link

Sample request?

@filipelinhares
Copy link
Author

fetch(functionURL, {
      method: 'POST',
      headers: new Headers({
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json'
      }),
      body
})

I don't know if it is the answer you are looking for. Can you be more specific in that case?

@BossBele
Copy link

Yes it is. Thank you!

@dickynasje
Copy link

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment