nestjs / swagger

OpenAPI (Swagger) module for Nest framework (node.js) :earth_americas:
https://nestjs.com
MIT License
1.68k stars 466 forks source link

Global `.addSecurityRequirements()` is overrided by local `@ApiSecurity()` #2222

Open zetaraku opened 1 year ago

zetaraku commented 1 year ago

Is there an existing issue for this?

Current behavior

If any @ApiSecurity() decorator is present on a route, then the Available authorizations registered by global .addSecurityRequirements() on the route are gone.

Minimum reproduction code

https://github.com/zetaraku/nest-demo

Steps to reproduce

  1. Run npm install
  2. Run npm run start:dev
  3. Goto the /api route
  4. Click the lock icons on both /without-decorator and /with-decorator route

Expected behavior

The local security requirements should be merged with the global security requirements so that both requirements are present.

Package version

6.1.4

NestJS version

9.0.0

Node.js version

16.17.0

In which operating systems have you tested?

Other

No response

kamilmysliwiec commented 1 year ago

Would you like to create a PR for this?

zetaraku commented 1 year ago

After doing some inspection, I found the cause of this behavior is described in OpenAPI Specification, which describes the root security field as:

A declaration of which security mechanisms can be used across the API. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. Individual operations can override this definition. To make security optional, an empty security requirement ({}) can be included in the array.

The root security field seems to be intended as a default setting when security is not presented on a route. (It seems not that useful.)

Applying @ApiSecurity() on the controller instead works well and I think it is more reasonable than using a "global" setting.

Not sure if we need to change the behavior or update the docs. What do you think?

ronniehicks commented 1 month ago

Related to this, is there a way to indicate a single operation/controller as no security requirements?