What Is Swagger? How To Provide Security To Swagger?

Share on facebook
Share on google
Share on twitter
Share on linkedin
What Is Swagger

What is Swagger?

Swagger is the way of defining the structure of APIs (Application Programming Interface). Swagger is specifically developed for REST (Representational State Transfer) APIs, where REST is a Web based API. These APIs can be defined in a file, called Swagger file, which includes certain information like the type of data that needs to be sent in a request, the type of data that needs to be received as the response from the request sent, the server locations, authorization for the request, status codes etc. The Swagger Specification is also known as the Open API Specification (OAS). Using swagger, APIs can be created in either YAML or JSON. The different tools used for swagger are: Swagger Editor, Swagger UI and Swagger Codegen. The latest version of OAS is OpenAPI 3.0.

Below given is the basic structure of swagger in YAML:

				
					openapi: 3.0.0
info:
  title: Sample API
  description: Optional multiline or single-line description in [CommonMark](http://commonmark.org/help/) or HTML.
  version: 0.1.9

servers:
  - url: http://api.example.com/v1
    description: Optional server description, e.g. Main (production) server
  - url: http://staging-api.example.com
    description: Optional server description, e.g. Internal staging server for testing

paths:
  /users:
    get:
      summary: Returns a list of users.
      description: Optional extended description in CommonMark or HTML.
      responses:
        '200':    # status code
          description: A JSON array of user names
          content:
            application/json:
              schema: 
                type: array
                items: 
                  type: string
				
			

How to provide security to Swagger / OAS?

API Security can be provided using Authentication and Authorization mechanisms. Authentication is the method of validating users by means of Username and Password and Authorization is the method of allowing users to access the data. OpenAPI uses a ‘security scheme’ for providing authentication and authorization.

Different security schemes for providing security in OpenAPI 3.0 are:

  1. HTTP authentication schemes

  2. API Keys

  3. OAuth2

  4. OpenID Connect Discovery

How to describe security in OpenAPI 3.0?

In OpenAPI, security is described using the keywords securitySchemes and security. The keyword securitySchemes is used to define all the security schemes associated with the API and the keyword security is used to apply the defined schemes to the specific operations or to the entire API.

The main steps in describing security:

  1. Defining securitySchemes

  2. Applying security

1. Defining securitySchemes

The security schemes should be defined in components/securitySchemes section of the API. This section includes various schemes and its type for defining security schemes.

        Type
Scheme
      http Basic, Bearer
      apiKey API keys and Cookie authentication
      oauth2 OAuth 2
      openIdConnect OpenID Connect Discovery

				
					components:
  securitySchemes:

    BasicAuth:
      type: http
      scheme: basic

    BearerAuth:
      type: http
      scheme: bearer

    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key

    OpenID:
      type: openIdConnect
      openIdConnectUrl: https://example.com/.well-known/openid-configuration

    OAuth2:
      type: oauth2
      flows:
        authorizationCode:
          authorizationUrl: https://example.com/oauth/authorize
          tokenUrl: https://example.com/oauth/token
          scopes:
            read: Grants read access
            write: Grants write access
            admin: Grants access to admin operations
				
			

2. Applying Security

To apply the security schemes that are defined in the securitySchemes section, use the security section on the root level or operation level. When using the root level, the security schemes will be applied to the whole API (all API operations) and the operation level applies the security schemes to individual operations.

Security section on root level:

				
					security:
  - ApiKeyAuth: []
  - OAuth2:
      - read
      - write

# The syntax is:
# - scheme name:
#     - scope 1
#     - scope 2
				
			

Security section on operation level:

				
					paths:
  /billing_info:
    get:
      summary: Gets the account billing info
      security:
        - OAuth2: [admin]   # Use OAuth with a different scope
      responses:
        '200':
          description: OK
        '401':
          description: Not authenticated
        '403':
          description: Access token does not have the required scope
  
  /ping:
    get:
      summary: Checks if the server is running
      security: []   # No security
      responses:
        '200':
          description: Server is up and running
        default:
          description: Something is wrong
				
			

Scopes:

OAuth2 and OpenID Connect schemes use scope for controlling user permissions. Scope can be read, written etc. Other schemes (Basic, Bearer, API keys and others) do not use scopes, so their security entries denote an empty array [].

				
					security:
  - OAuth2:
      - scope1
      - scope2
  - OpenId:
      - scopeA
      - scopeB
  - BasicAuth: []
				
			
				
					# Instead of this:
# security:
#   - OAuth2:
#       - read
#       - write

# Do this:
paths:
  /users:
    get:
      summary: Get a list of users
      security:
        - OAuth2: [read]     # <------
      ...

    post:
      summary: Add a user
      security:
        - OAuth2: [write]    # <------
      ...
				
			

Using Multiple Authentication Types:

REST APIs also support using multiple authentication types together. The authentication types can be combined in the security section using logical OR and AND operations. The logic is shown below.

				
					security:    # A OR B
  - A
  - B
				
			
				
					security:    # A AND B
  - A
    B
				
			
				
					security:    # (A AND B) OR (C AND D)
  - A
    B
  - C
    D
				
			

Here, we can use either Basic authentication or an API key:

				
					security:
  - basicAuth: []
  - apiKey: []
				
			

Here, the API requires a pair of API keys to be included in requests:

				
					security:
  - apiKey1: []
    apiKey2: []
				
			

Here, we can use either OAuth 2 or a pair of API keys:

				
					security:
  - oauth2: [scope1, scope2]
  - apiKey1: []
    apiKey2: []
				
			
Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

Recent Posts

Follow Us

Web Application Firewall Solution