Both from a security and data quality perspective, it is advised to validate request and response payloads in Azure API Management. This blog shows how to do this.
Validate-content policy
The validate-content policy validates the size or content of a request or response body against one or more schemas. Let’s have a look at the different steps you have to take, when crafting an API yourself.
Upload schema
Under the Schemas tab, you can upload the schemas with a specific name. Below you can find an example of a JSON schema, which only validates on required properties. Preferably, you add more constraints to your schemas, but this is just for demo purposes.
{ "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": { "specversion": { "type": "string", "required": true }, "type": { "type": "string", "required": true }, "source": { "type": "string" }, "id": { "type": "string", "required": true }, "time": { "type": "string", "required": true }, "data": { "type": "object" } } }
Add an API operation
Add an API operation. Ensure that within the Frontend configuration, on the Request or Response tab, you add a representation for every allowed Content-Type. In my case, this is application/json.
Configure the policy
Configure the policy to validate the request payload against the uploaded schema. If there is no Content-Type header provider, we should assume application/json.
<inbound> <base /> <validate-content unspecified-content-type-action="prevent" max-size="102400" size-exceeded-action="prevent"> <content-type-map missing-content-type-value="application/json" /> <content type="application/json" validate-as="json" schema-id="sales-customer-won-v1" action="prevent" /> </validate-content> </inbound>
The result
If you call the API with an invalid payload (missing time property), you get the following error:
{ "statusCode": 400, "message": "Body of the request does not conform to the definition which is associated with the content type application/json. Required properties are missing from object: time. Line: 5, Position: 1" }
{ "statusCode": 400, "message": "Unspecified content type application/json is not allowed." }
Conclusion
A simple way to enforce payload validation in API Management, with a serious caveat on the representation that should be added!
Sharing is caring!
Toon