OpenAPI restrict path to 'admin' users

Viewed 175

In OpenAPI, how to you restrict a given action (e.g. GET /users) to users with a specific role (e.g. admin)?

Example, where the list of users should only be accessible to admin users:

paths:
  /users:
    get:
      # TODO: restrict access to users with 'admin' role
      summary: Get list of all users
      security:
        - BearerAuth: []
      operationId: getUsers      
      responses:
        200:
          description: successful operation      
          content:
            application/json:
              schema:
                type: object
                properties:
                  users:
                    type: array
                    items:
                      $ref: '#/components/schemas/User'
1 Answers

Bearer Authorization does not support access scopes as defined with OpenAPI. You have a few options:

Use A Description

Use a description to explain to readers of your definition that these endpoints require an auth token belonging to an admin user. This is the simplest solution, though this won't allow tooling to automatically enforce this criteria from your OpenAPI spec, so you'll need to manually control this in your own code.

get:
  description: Get list of all users. Limited to admin users.

Use An Extension

Write an extension to formally describe the criteria necessary for your auth tokens. OpenAPI allows the use of extra properties for defining properties and behaviors that are specific to your implementation that don't fit the generic case. You can write tooling and scripts to process this property to enforce behavior as you see fit.

get:
  x-authRoles: ['admin']

Use OAuth 2.0

Use OAuth 2.0 or another security scheme that supports access scopes by design. You may find this adds additional security benefits, as all tooling around OAuth already expects access scopes, so you may have an easier time with this particular problem, as you won't have to roll your own implementation.

get:
  security: 
    - oAuthSample: 
      - admin
Related