Reputation: 10759
I have a node.js app that used to work when basicAuth was a module of node. Below code would popup a password and username prompt when visiting app.
// start the UI
var app = express();
app.use(express.basicAuth('me', 'openforme'));
app.use(kue.app);
app.listen(3001);
Now that basicAuth was removed as a module, from node, I am using express-basic-auth. When using the below code I get a 401 unauthorized error because it is not giving me a username and password popup prompt like basicAuth did?
// start the UI
var app = express();
var basicAuth = require('express-basic-auth');
app.use(basicAuth({
users: { 'me': 'openforme' }
}));
app.use(kue.app);
app.listen(3001);
Upvotes: 16
Views: 19326
Reputation: 586
Now there is an out-of-the-box option from express-basic-auth
. The Challenge property.
app.use(basicAuth({
challenge: true,
users: { 'me': 'openforme' }
}));
Upvotes: 33
Reputation: 3666
I know this is very late to the party, but your desired behavior can be achieved by using basic-auth
like so:
const express = require('express')
const auth = require('basic-auth')
const app = express()
// Ensure this is before any other middleware or routes
app.use((req, res, next) => {
let user = auth(req)
if (user === undefined || user['name'] !== 'USERNAME' || user['pass'] !== 'PASSWORD') {
res.statusCode = 401
res.setHeader('WWW-Authenticate', 'Basic realm="Node"')
res.end('Unauthorized')
} else {
next()
}
})
Upvotes: 5