API / Swagger Interview questions
How do you handle authentication in Swagger UI for testing secured endpoints?
Swagger UI provides a global "Authorize" button (rendered whenever the spec defines one or more securitySchemes) that opens a dialog for entering credentials matching each declared scheme, and those credentials are then automatically attached to every subsequent "Try it out" request that requires them, without needing to re-enter them for each individual endpoint.
- Click the Authorize button at the top of the Swagger UI page.
- For an API key scheme, enter the key value directly; for HTTP bearer/basic auth, enter the token or credentials; for OAuth2, the dialog initiates the configured flow (e.g. redirecting to an authorization server for the authorization code flow).
- Swagger UI stores the resulting credential in memory for the current browser session.
- On every subsequent "Try it out" request for an operation whose
securityrequirement matches the authorized scheme, Swagger UI automatically attaches the credential — as a header, query parameter, or cookie, per the scheme'sinfield.
This only works correctly if the operation's security requirement and the securitySchemes definition are both correctly declared in the spec; a common documentation gap is a team securing an endpoint in the actual implementation but forgetting to add the corresponding security field to that operation in the OpenAPI document, which makes Swagger UI send unauthenticated test requests that then fail against the real, secured server.
More Related questions...