Created
July 28, 2020 11:43
-
-
Save steelx/3f0de01d033ed0b1f2f8870b67969f86 to your computer and use it in GitHub Desktop.
Node js AUTH middleware
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 cors = require('cors')({origin: true}); | |
const cookieParser = require('cookie-parser')(); | |
// API | |
const app = express(); | |
// Express middleware that validates Firebase ID Tokens passed in the Authorization HTTP header. | |
// The Firebase ID token needs to be passed as a Bearer token in the Authorization HTTP header like this: | |
// `Authorization: Bearer <Firebase ID Token>`. | |
// when decoded successfully, the ID Token content will be added as `req.user`. | |
const validateFirebaseIdToken = async (req, res, next) => { | |
console.log('Check if request is authorized with Firebase ID token'); | |
if ((!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) && | |
!(req.cookies && req.cookies.__session)) { | |
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.'); | |
res.status(403).send('Unauthorized'); | |
return; | |
} | |
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 | |
res.status(403).send('Unauthorized'); | |
return; | |
} | |
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; | |
} | |
}; | |
app.use(cors); | |
app.use(cookieParser); | |
app.use(validateFirebaseIdToken); | |
app.get('/hello', (req, res) => { | |
res.send(`Hello ${req.user}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment