OAuth2 security requirement requires a scope not declared in the referenced security scheme

Description

The OAuth2 security requirement in the security field requires a scope that has not been defined in the security scheme of your API. The security field specifies what kind of authentication your API requires.

For more details, see the OpenAPI Specification.

Example

The following is an example of how this type of risk could look in your API definition:

{
  ...
  "securityDefinitions": {
    "OAuth2": {
      "type": "oauth2",
      "flow": "accessCode",
      "scopes": {
        "read": "read objects in your account",
        "write": "write objects to your account",
      },
      "authorizationUrl": "https://example.com/oauth/authorize",
      "tokenUrl": "https://example.com/oauth/token", 
    }
  },
  ...
{
  "security" : [
    "OAuth2": [ "readWrite" ]
  ]
}

Possible exploit scenario

If you do not lock down all scopes the OAuth 2 security requirement can use, attackers could try to introduce their scopes to fill the gap.

Attackers could, for example, specify an arbitrary scope containing an SQL injection or buffer overflow attack that is triggered when your API requests a token from the token URL. By limiting the scopes that the OAuth flow can use only to those defined in the OAuth2 security scheme, you ensure that only the strings you have specified are allowed through to the token endpoint. An unrecognized scope in the token request could also lead the attackers gaining extended permissions to access the your resources.

Remediation

Ensure that all OAuth2 scopes referenced in the security requirements have a match in the OAuth2 security scheme, or remove the undefined scopes.

{
  ...
  "securityDefinitions": {
    "OAuth2": {
      "type": "oauth2",
      "flow": "accessCode",
      "scopes": {
        "read": "read objects in your account",
        "write": "write objects to your account",
      },
      "authorizationUrl": "https://example.com/oauth/authorize",
      "tokenUrl": "https://example.com/oauth/token", 
    }
  },
  ...
{
  "security" : [
    "OAuth2": [ "read", "write" ]
  ]
}