Closed lovedoodle closed 5 years ago
@LionC I'm really interested in doing this as well. Can the module do this currently?
Looks like it is planned for v2. See #13.
Can't you simply use an express router and only use it in there or only specify it for your desired routes? I mean this is a standard express middleware after all. At least that's how I am doing it. Just don't use it globally with app.use()
if you don't want it globally.
As @num-lock wrote, just use
app.get('/route', basicAuth(...), (req, res) => {...});
instead of
app.use(basicAuth(...));
Yes, or even better: Use a Router
. That's what they are there for after all. Putting everything directly into app
is bad practice anyways.
const router = express.Router();
router.get('/a', (req, res) => {...});
router.get('/b', (req, res) => {...});
app.use('/api', basicAuth(...), router);
// /api/a and /api/b now use basic-auth middleware
Alternatively you can also do router.use(basicAuth(...))
first instead of putting it into app.use
when applying the route. Either way it's a lot more concise and transparent than having the middleware itself handle which routes to hook on.
Related question:
Can basicAuth challenge a single user on multiple routes?
/** everyone enters this password **/
app.get('/', basicAuth({
users: { preview: 'pass123' },
challenge: true
}));
/** hidden route for internal use **/
app.get('internal/', basicAuth({
users: { internal: 'passabc' },
challenge: true
}));
I was thinking maybe I'd need to have two different instances of basicAuth, but that didn't work either:
const basicAuthPreview = require('express-basic-auth');
const basicAuthInternal = require('express-basic-auth');
I have a couple public routes where I don't want there to be any baisc auth requirements. Does this package offer a way to do that?