API / Swagger Interview questions
How does Swagger support security schemes like OAuth2 and API keys?
OpenAPI describes authentication mechanisms through securitySchemes defined under components, and then references those schemes — either globally or per-operation — via a security field, so tools like Swagger UI know how to prompt for and attach credentials when testing an endpoint.
components: securitySchemes: apiKeyAuth: type: apiKey in: header name: X-API-Key oauth2: type: oauth2 flows: authorizationCode: authorizationUrl: https://auth.example.com/authorize tokenUrl: https://auth.example.com/token scopes: read: Read access write: Write access security: - apiKeyAuth: []
OpenAPI supports several scheme types beyond these two examples — HTTP basic/bearer auth, OpenID Connect, and mutual TLS — and OAuth2 specifically supports multiple flow types (authorization code, client credentials, implicit, password) each with its own set of required URLs and scopes.
Swagger UI reads this configuration to render an "Authorize" button that prompts for the right credentials for the declared scheme — an API key field, or a full OAuth2 login redirect — and then automatically attaches the resulting token or key to every subsequent "Try it out" request made from the UI.
More Related questions...