Review API key authentication (OpenAPI 3.0)

Review where API keys are sent and how exposure is prevented

Description

apiKey is a valid authentication method; declaring its security scheme does not itself expose a secret key. However, a key sent in the query string may appear in URL logs, so review its transport and handling.

Potential impact

Someone who obtains an exposed key may call the API with the permissions granted to that key.

Remediation

Send API keys over HTTPS in a header instead of the URL. Keep keys out of logs, and revoke and replace exposed keys. If you need delegated user authorization, consider an appropriate method such as OAuth2.

Examples

These excerpts show one option: replacing a query-string API key with OAuth2. Keeping API keys while using HTTPS and headers is also possible. Changing the scheme alone does not change authentication behavior; configure the server and clients accordingly.

Before

json
{
  "openapi": "3.0.0",
  "security": [
    {
      "apiKeyAuth": []
    }
  ],
  "components": {
    "securitySchemes": {
      "apiKeyAuth": {
        "type": "apiKey",
        "name": "X-API-Key",
        "in": "query"
      }
    }
  }
}

After

json
{
  "openapi": "3.0.0",
  "security": [
    {
      "oauthAuth": []
    }
  ],
  "components": {
    "securitySchemes": {
      "oauthAuth": {
        "type": "oauth2",
        "flows": {
          "authorizationCode": {
            "authorizationUrl": "https://example.com/api/oauth/dialog",
            "tokenUrl": "https://example.com/api/oauth/token",
            "scopes": {
              "read:pets": "read your pets"
            }
          }
        }
      }
    }
  }
}

References