首页 > 解决方案 > JSON Schema 4 仅验证一个定义

问题描述

我希望我的 HTTP 请求正文将接受如下内容:

{
    "grant_type": "refresh_token", // "refresh_token" or "password"
    "client_id": "my-client",      // NEVER CHANGE
    "refresh_token": "XXX"
}

或者

{
    "grant_type": "password",   // "refresh_token" or "password"
    "client_id": "my-client",   // NEVER CHANGE
    "username": "XXX",
    "password": "XXX",
}

如您所见,格式更改基于grant_type. 所以我定义了这个模式:

{
  "definitions": {
    "username_and_password": {
        "type": "object",
        "properties": {
            "grant_type": { "type": "string", "enum": ["password"] },
            "client_id": { "type": "string", "enum": ["my-client"] },
            "username": { "type": "string" },
            "password": { "type": "string" }
        },
        "required": ["grant_type", "client_id", "username", "password" ]
    },
    "refresh_token": {
        "type": "object",
        "properties": {
            "grant_type": { "type": "string", "enum": ["refresh_token"] },
            "client_id": { "type": "string", "enum": ["my-client"] },
            "refresh_token": { "type": "string" }
        },
        "required": [ "grant_type", "client_id", "refresh_token" ]
    }
  },

  "oneOf": [
    { "$ref": "#/definitions/username_and_password" },
    { "$ref": "#/definitions/refresh_token" }
  ],

  "additionalProperties": false
}

我将其用作 API Gateway 的模型,但它拒绝了我发送的所有内容。错误在哪里?

标签: aws-api-gatewayjsonschema

解决方案


additionalProperties虚假是你的问题。

它不能“透视”oneOf$ref引用。

如果“additionalProperties”具有布尔值 false...

在这种情况下,实例的验证取决于“properties”和“patternProperties”的属性集。

https://datatracker.ietf.org/doc/html/draft-fge-json-schema-validation-00#section-5.4.4.4

对它的工作原理有更多解释,我们在草案 5 之后对其进行了澄清,但本质上......

additionalProperties适用于未properties在与 相同的模式对象级别中定义的所有属性additionalProperties

因为您的架构只有additionalProperties并且没有properties定义,所以所有属性都会导致验证失败。

您可以通过定义属性来解决这个问题,其中每个属性的值都是空模式。从草案 5 开始,您可以将true其用作值,因为truefalse是有效的“模式”。


推荐阅读