Created
February 14, 2020 15:51
-
-
Save DrDanL/ac72f88e239df4303a0350ae58f63b81 to your computer and use it in GitHub Desktop.
Firebase RESTful server API - Authentication validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const http = require('http'); | |
const https = require('https'); | |
const app = express(); | |
const router = express.Router(); | |
const cors = require('cors') | |
const admin = require('firebase-admin'); | |
const bodyParser = require('body-parser'); | |
const functions = require('firebase-functions'); | |
// Initialize Admin SDK for use in the server | |
try { | |
admin.initializeApp(); | |
} catch (e) {} | |
//Build authenticatin system to verify token requests | |
const validateFirebaseIdToken = async (req, res, next) => { | |
console.log('Request validateFirebaseIdToken: ' + req.get('Authorization')) | |
if ((!req.headers.authorization || !req.headers.authorization.startsWith('Bearer'))) { | |
console.error('No Firebase ID token was passed as a Bearer token in the Authorization header.', | |
'Make sure you authorize your request by providing the following HTTP header:', | |
'Authorization: Bearer <Firebase ID Token>', | |
'or by passing a "__session" cookie.') | |
return res.status(403).send({ | |
status: 403, | |
msg: 'Unauthorised', | |
payload: null | |
}) | |
} | |
let idToken; | |
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) { | |
console.log('Found "Authorization" header'); | |
// Read the ID Token from the Authorization header. | |
idToken = req.headers.authorization.split('Bearer ')[1]; | |
} else if (req.cookies) { | |
console.log('Found "__session" cookie'); | |
// Read the ID Token from cookie. | |
idToken = req.cookies.__session; | |
} else { | |
// No cookie present | |
return res.status(403).send({ | |
status: 403, | |
msg: 'Unauthorised', | |
payload: null | |
}) | |
} | |
try { | |
const decodedIdToken = await admin.auth().verifyIdToken(idToken); | |
console.log('ID Token correctly decoded: ', decodedIdToken); | |
req.user = decodedIdToken; | |
next(); | |
return; | |
} catch (error) { | |
console.error('Error while verifying Firebase ID token:', error); | |
res.status(403).send('Unauthorized'); | |
return; | |
} | |
}; | |
//Enable cors | |
router.use(cors({ | |
origin: true | |
})) | |
// Support JSON-encoded bodies. | |
router.use(bodyParser.json()); | |
// Support URL-encoded bodies. | |
router.use(bodyParser.urlencoded({ | |
extended: true | |
})); | |
//Authentication - this projects all routes | |
app.use(validateFirebaseIdToken); | |
//GET: Complete user payload | |
router.get('/', function(req, res) { | |
res.status(401).send('UNAUTHORIZED REQUEST!'); | |
}); | |
router.get('/test', function(req, res) { | |
console.log('User requesting access: ' + req.user) | |
}); | |
///////////////////////// | |
//Push API | |
//////////////////////// | |
app.use('/restful-api/', router); | |
exports.RestfulAPI = functions.https.onRequest(app); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"firestore": { | |
"rules": "firestore.rules", | |
"indexes": "firestore.indexes.json" | |
}, | |
"hosting": { | |
"public": "public", | |
"ignore": [ | |
"firebase.json", | |
"**/.*", | |
"**/node_modules/**" | |
], | |
"rewrites": [{ | |
"source": "/restful-api/**", | |
"function": "RestfulAPI" | |
}] | |
}, | |
"storage": { | |
"rules": "storage.rules" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment