HTTP Basic Authentication with Express
Updated: 03 September 2023
In a new file, define the middleware using the following:
1const authenticate = (req, res, next) => {2 const auth = { login: process.env.BASIC_UN, password: process.env.BASIC_PW }3
4 const b64auth = (req.headers.authorization || '').split(' ')[1] || ''5 const [login, password] = new Buffer(b64auth, 'base64').toString().split(':')6
7 // Verify login and password are set and correct8 if (login && password && login === auth.login && password === auth.password) {9 // Access granted...10 return next()11 } else {12 res.status(401).send('Authentication required.') // custom message13 }14}15
16module.exports = authenticate
The middleware can then be used in an Express Endpoint or for all endponits using either:
- For all endpoints
1const auth = require('./authorize.js')2
3app.use(auth)
- For a specific endpoint
1const auth = require('./authorize.js')2
3app.get('/secret-stuff', auth, secretStuffHandler)