cdimascio / express-openapi-validator

🦋 Auto-validates api requests, responses, and securities using ExpressJS and an OpenAPI 3.x specification
MIT License
909 stars 206 forks source link

"Basic" authentication doesn't return WWW-Authenticate header on failure #471

Open geogeim opened 3 years ago

geogeim commented 3 years ago

I registered a basic security schema with my own validateSecurity.handlers for basic auth. When the user enters the URL in the browser he doesn't get the login prompt because the authentication doesn't return the "WWW-Authenticate" header in the response and just fails with "Authorization header required"

That means i have to work around it by adding this in the global error handler

      if(error.path === '/users/export' && error.status === 401) {
        res.set('WWW-Authenticate', 'Basic realm="ugh"');
      }

Which kinda defeats the purpose of the security handler in the first place :(

cdimascio commented 3 years ago

@geogeim good point. the challenge here is where to find the realm. OpenAPI doesn't define a property in the schema for an api devto provide it. Potentially, we can provide the response object to the security handler and let the dev set the 'WWW-Authenticate header. we might also define a vendor extension e.g. x-eov-realm to enable a user to set the realm directly in the spec. i'm open to suggestions

ahilke commented 3 years ago

@cdimascio What about just using WWW-Authenticate: Basic? According to the specification, this should be valid.

MDN says:

realm=<realm> A description of the protected area. If no realm is specified, clients often display a formatted hostname instead.

I verified this behaviour in Chromium and Firefox working like intended, i.e. showing a login popup. I tested it with this demo project (although it lacks documentation).

I never came across a use case for using realms, never mind multiple realms, so I cannot say what the implications would be. But it would allow to cover the basic and common use case without needing to add any attribute to the OpenAPI spec.

If you agree, I could take a stab at this sometime.

cdimascio commented 3 years ago

That will be great. Please do. It makes for a good launching point.