Created
November 22, 2020 23:37
-
-
Save javascripto/6232f03da0dbcd3b2edb2987816081a4 to your computer and use it in GitHub Desktop.
Express Basic Authentication middleware
This file contains hidden or 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 app = require('express')() | |
| const defaultConfig = { | |
| users: { | |
| user: 'password' | |
| } | |
| } | |
| function basicAuth({ users } = defaultConfig) { | |
| function reject(response) { | |
| response.set('WWW-Authenticate', 'Basic') | |
| return response.status(401).end() | |
| } | |
| return function middleware(request, response, next) { | |
| if (!request.headers.authorization) return reject(response) | |
| const [_, token] = request.headers.authorization.split(' ') | |
| const [user, pass] = Buffer.from(token, 'base64').toString().split(':') | |
| if (user in users && users[user] == pass) return next() | |
| return reject(response) | |
| } | |
| } | |
| app | |
| .get('/logout', (request, response) => { | |
| return response.status(401).send() | |
| }) | |
| .get('/login', basicAuth(), (request, response) => { | |
| return response.end('Authenticated') | |
| }) | |
| .listen(8080, () => { | |
| console.clear() | |
| console.log('🚀️ Running on http://localhost:8080') | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment