LionC / express-basic-auth

Plug & play basic auth middleware for express
325 stars 57 forks source link

How do I use basic auth but only for certain routes? #14

Closed lovedoodle closed 5 years ago

lovedoodle commented 5 years ago

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?

kitajchuk commented 5 years ago

@LionC I'm really interested in doing this as well. Can the module do this currently?

ghost commented 5 years ago

Looks like it is planned for v2. See #13.

num-lock commented 5 years ago

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.

mdorda commented 5 years ago

As @num-lock wrote, just use

app.get('/route', basicAuth(...), (req, res) => {...});

instead of

app.use(basicAuth(...));
num-lock commented 5 years ago

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.

horak commented 1 year ago

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');