LionC / express-basic-auth

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

Create open endpoints #13

Closed alvarolorentedev closed 6 years ago

alvarolorentedev commented 6 years ago

Is it posible to whitelist some endpoints of my express api to bypass the authentication/authorization using the module?

LionC commented 6 years ago

That is possible in the way express handles middleware - you can attach middleware only to the routers / routes that you want to protect, instead of attaching it to the whole app. If you need an example on how to do that, feel free to ask and I will write one :-)

alvarolorentedev commented 6 years ago

thanks for the fast response 😃 .

that is true'ish I think that authorization at least for me is a top level concern and not route base, so declaring it on each router could be very complex for me because y go quite granular on it for my api designs.

From the request object of the middlewares it is possible to get the path through 2 fields (originalUrl and path).

    app.use((req, res,next) =>{
        console.log(originalUrl) ///rest/v1/prod/.../images
        console.log(path) ///rest/v1/prod/.../images
        next()
    })

So i think is quite feasable to add whitelisting at a configuration level. Do you think this is a functionality valid for your middleware? do you accept PRs?. If not alternativelly will it be possible to pass to the authorizer option the request to work around this?

LionC commented 6 years ago

Passing req as a third argument to the authorizer sounds like a good idea anyways - and it enables you to build a whitelist very easily without making express-basic-auth more complex (I try to keep it as simple as possible).

I will do that!

alvarolorentedev commented 6 years ago

thanks :) , that would be awesome

LionC commented 6 years ago

Hm. Passing req would be a breaking change (as it would break the signature of the async authorizer signature).

So I will move this to v2, which will also be after the rewrite in typescript.

felixSchober commented 6 years ago

I had the same problem and "solved" it for now by adding a middleware-wrapper around the basic auth call

const basicAuthMiddleware = basicAuth({ 'admin': 'supersecret' });
app.use((req, res, next) => shouldAuthenticate(req) ? basicAuthMiddleware(req, res, next) : next());

In the shouldAuthenticate method you can then decide (based on the path) if you want to want to use the auth middleware (return true) or proceed without authentication (return false)

LionC commented 6 years ago

I will close the issue for now, as the passing req idea is accepted and moved to a release. Thanks for the input!