Skip to content

OpenAPI Security — Defining Authentication and Authorization

DodaTech Updated 2026-06-28 5 min read

In this tutorial, you will learn about OpenAPI Security. We cover key concepts, practical examples, and best practices to help you master this topic.

OpenAPI security schemes define how clients authenticate to your API, supporting API keys, HTTP authentication (Bearer, Basic), OAuth2 flows, and Openid Connect discovery.

In this tutorial, you will learn how to define security schemes in OpenAPI, apply them globally or per-operation, and document authentication requirements clearly for developers.

What You'll Learn

You will learn all supported security scheme types, how to define them in components, how to apply security requirements globally and per-endpoint, and best practices for documenting authentication flows.

Why It Matters

Authentication is the first barrier every developer faces. Unclear authentication documentation is the top reason developers abandon API integration. Well-defined security schemes generate accurate documentation and client code.

Real-World Use

DodaTech APIs support multiple authentication methods. Public endpoints use API keys for simplicity. Admin endpoints require Bearer JWT tokens. Partner integrations use OAuth2 with authorization code flow. Each method is documented in the OpenAPI spec.

flowchart LR
  A[Security Scheme] --> B[API Key]
  A --> C[HTTP Auth]
  A --> D[OAuth2]
  A --> E[OpenID Connect]
  B --> F[Request Flow]
  C --> F
  D --> F
  A:::current
  classDef current fill:#f90,color:#fff,stroke:#333,stroke-width:2px

Security Scheme Types

API Key Authentication

API keys are simple tokens sent in headers, query parameters, or cookies.

components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key
      description: API key obtained from the developer dashboard

HTTP Authentication

HTTP authentication includes Bearer tokens and Basic auth.

components:
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: JWT token obtained from the authentication endpoint
    BasicAuth:
      type: http
      scheme: basic
      description: Base64-encoded username:password

OAuth2

OAuth2 supports multiple authorization flows.

components:
  securitySchemes:
    OAuth2:
      type: oauth2
      flows:
        authorizationCode:
          authorizationUrl: https://auth.dodatech.com/oauth/authorize
          tokenUrl: https://auth.dodatech.com/oauth/token
          refreshUrl: https://auth.dodatech.com/oauth/token
          scopes:
            read:users: Read user profile data
            write:users: Create and update users
            admin:users: Administer all user accounts
        clientCredentials:
          tokenUrl: https://auth.dodatech.com/oauth/token
          scopes:
            api:read: Read access to API resources
            api:write: Write access to API resources
        implicit:
          authorizationUrl: https://auth.dodatech.com/oauth/authorize
          scopes:
            read:users: Read user data
        password:
          tokenUrl: https://auth.dodatech.com/oauth/token
          scopes:
            api:full: Full API access

OpenID Connect

OpenID Connect uses a discovery URL.

components:
  securitySchemes:
    OpenID:
      type: openIdConnect
      openIdConnectUrl: https://auth.dodatech.com/.well-known/openid-configuration

Applying Security

Global Security

Apply security to all operations by default.

security:
  - BearerAuth: []

Per-Operation Security

Override global security for specific operations.

paths:
  /users:
    get:
      security:
        - BearerAuth: [read:users]
      responses:
        "200":
          description: User list
    post:
      security:
        - BearerAuth: [write:users]
      responses:
        "201":
          description: User created
  /health:
    get:
      security: []
      responses:
        "200":
          description: Health check (no auth required)
  /public/docs:
    get:
      security: []
      responses:
        "200":
          description: Public documentation

Multiple Security Schemes

Clients can satisfy multiple schemes simultaneously.

security:
  - BearerAuth: []
    ApiKeyAuth: []
  - OAuth2: [read:users]

This means the client must satisfy both BearerAuth AND ApiKeyAuth, OR satisfy OAuth2 with the read:users scope.

Documenting Authentication Flow

Beyond the security scheme definition, document the complete authentication flow.

paths:
  /auth/login:
    post:
      summary: Obtain authentication token
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - email
                - password
              properties:
                email:
                  type: string
                  format: email
                password:
                  type: string
                  format: password
      responses:
        "200":
          description: Authentication successful
          content:
            application/json:
              schema:
                type: object
                properties:
                  token:
                    type: string
                    description: JWT access token
                  refreshToken:
                    type: string
                    description: Token for obtaining new access tokens
                  expiresIn:
                    type: integer
                    description: Token lifetime in seconds
  /auth/refresh:
    post:
      summary: Refresh authentication token
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                refreshToken:
                  type: string
      responses:
        "200":
          description: New token issued

Common Mistakes

  1. Missing security definitions — Defining security at the operation level without defining the scheme in components. Every security reference must point to a defined securityScheme.

  2. Not documenting public endpoints — Forgetting to add security: [] for public endpoints. Without this, the global security applies and generated clients try to authenticate.

  3. Missing scope documentation — Not describing what each OAuth2 scope grants access to. Developers need to know which scopes to request.

  4. No token endpoint documentation — Not documenting how to obtain tokens. Include the login endpoint with request and response examples.

  5. Mixed security methods without guidance — Offering multiple auth methods without explaining which one to use and when.

Practice Questions

  1. What are the four types of security schemes in OpenAPI?
  2. How do you apply security to all operations globally?
  3. How do you mark an endpoint as public (no authentication)?
  4. What is the purpose of OAuth2 scopes?
  5. How does OpenID Connect differ from OAuth2 in OpenAPI?

Challenge

Design a complete security scheme for a multi-tenant SaaS API. Support three authentication methods: API key for server-to-server, Bearer JWT for user sessions, and OAuth2 for third-party integrations. Define scopes for read, write, and admin access. Document the login, refresh, and logout endpoints.

FAQ

Can I use multiple security schemes on one endpoint?

Yes. List multiple schemes in the security array. The client must satisfy all listed schemes for that endpoint (AND logic). Use separate entries for OR logic.

How do I document API key creation?

Create a separate endpoint path for generating API keys, typically in the developer dashboard section. Document how users can create and manage keys through the dashboard.

What is the bearerFormat field used for?

bearerFormat is informational. It tells developers what format the token uses (JWT, opaque, etc.). It does not affect validation.

Should I include the auth endpoint in the same OpenAPI spec?

Yes. Documenting auth endpoints in the same spec provides a complete picture. Mark them with security: [] since they do not require prior authentication.

How do I handle refresh tokens?

Document the refresh endpoint alongside login. Specify the refresh token format, lifetime, and how to request new access tokens.

Mini Project

Create a complete security specification for a document editing API. Define API key auth for read-only access, Bearer JWT for user operations, and OAuth2 with authorization code flow for third-party integrations. Include scopes for doc:read, doc:write, doc:share, and doc:admin. Document the full authentication flow with login, register, and refresh endpoints.

What's Next

In the next lesson, you will learn how to use Swagger UI to render OpenAPI specs as interactive documentation pages.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro