I’m using the express-basic-auth library to protect a readme route in my Express.js application. I want the browser to prompt for credentials every time the user refreshes the page, closes and reopens the tab, or closes and reopens the browser. However, once the user logs in, the credentials are cached, and the browser doesn’t prompt again.
const basicAuth = require('express-basic-auth');
const express = require('express');
const path = require('path');
const app = express();
function myAuthorizer(username, password) {
try {
const userMatches = basicAuth.safeCompare(username, 'admin');
const passwordMatches = basicAuth.safeCompare(password, 'amin');
return userMatches && passwordMatches;
} catch (error) {
console.error('myAuthorizer', error);
return false;
}
}
app.use(
'/readme',
basicAuth({
authorizer: myAuthorizer,
challenge: true
}),
(req, res, next) => {
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
res.set('Pragma', 'no-cache');
res.set('Expires', '0');
res.set('Surrogate-Control', 'no-store');
next();
},
express.static(path.join(__dirname, '/readme'))
);
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Despite setting the cache-control headers, the browser does not prompt for credentials again on page refresh. How can I force the browser to show the basic auth prompt every time the page is refreshed or reopened?
Jaskaran is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.