How to apply security for each server URL in OpenAPI 3.0?

Viewed 132

I'm creating API documentation with OpenAPI 3.0.

I have security schemes defined like below.

components:
  securitySchemes:
    BasicAuth:
      type: http
      scheme: basic
    BearerAuth:
      type: http
      scheme: bearer

And I have two server URLs defined.

servers:
  - url: https://api.example.com
    description: Production server (uses live data)
  - url: https://sandbox-api.example.com
    description: Sandbox server (uses test data)

I want to apply BasicAuth security for only Sandbox server and BearerAuth for only Production server. How can I do that?

1 Answers

OpenAPI does not have a way to vary security per server. You can do the following:

  1. Provide separate API definitions for the Sandbox and Production servers.

or

  1. Specify both authentication methods in security and use description to explain which server uses which authentication method.
# Either Basic or Bearer auth
security:
  - BasicAuth: []
  - BearerAuth: []

components:
  securitySchemes:
    BasicAuth:
      type: http
      scheme: basic
      description: Use Basic authentication with the **Sandbox** server.
    BearerAuth:
      type: http
      scheme: bearer
      description: Use Bearer authentication with the **Production** server.
Related