{"id":10086,"date":"2021-04-26T15:31:23","date_gmt":"2021-04-26T14:31:23","guid":{"rendered":"https:\/\/staging-site.42crunch.com\/?p=10086"},"modified":"2022-11-22T11:27:09","modified_gmt":"2022-11-22T11:27:09","slug":"creating-high-quality-oas-definitions-with-springfox-part-2-data-validation","status":"publish","type":"post","link":"https:\/\/staging2022.42crunch.com\/creating-high-quality-oas-definitions-with-springfox-part-2-data-validation\/","title":{"rendered":"Creating High Quality OAS Definitions with Springfox – Part 2: Data Validation"},"content":{"rendered":"

In the first part of this blog<\/a>, we had covered the security aspects of Spring Boot Microservices and how to inject them into your code level to generate higher quality OAS (Swagger) files. In this second part, we will cover aspects regarding attributes, operations, and data. <\/span><\/p>\n

Data Validation for Secure APIs<\/strong><\/h2>\n

You must be aware that according to the way you have declared the parameters, response headers, definitions, and schemas in your OAS (Swagger) file, you might be able to get some data exposure or potential security scenario that can be exploited. <\/span><\/p>\n

\"\"<\/p>\n

Figure 1 – Data Validation Problems and Issues in the OAS (Swagger) file<\/span><\/em><\/p>\n

Using Spring Boot and Springfox, you can avoid such discrepancies and issues in your contract, allowing your API to reach a much higher audit score. Please, refer to the following best practices in this post. <\/span><\/p>\n

 <\/p>\n

Best Practice #1: Schemas PATTERN\/MIN LENGTH\/MAX LENGTH<\/h4>\n

This is very important in order to avoid attacks trying to break the kind of data that your API is ready to operate, please see the following code snippet:<\/span><\/p>\n

Code Definition<\/strong><\/p>\n

 @ApiModel(description = "Class representing a person tracked by the application.")\npublic class Person {\n   \t@Min(5)\n      @Max(50)\n   \t@NotNull\n   \t@NotBlank\n      @Pattern(regexp = Constants.ID_REGEX)\n   \t\n      private int id;\n      \n   \t@NotNull\n   \t@NotBlank\n   \t@Pattern(regexp = Constants.GENERIC_NAME_REGEX)\n        \t@Size(min = 5, max = 30)\n   \tprivate String firstName;\n<\/code><\/pre>\n

Swagger 2.0 Equivalent<\/strong><\/p>\n

 "firstName": {\n      \t"type": "string",\n      \t"minLength": 5,\n      \t"maxLength": 30,\n      \t"pattern": "^[a-zA-Z\\\\s_\\\\-]{2,50}$"\n    \t},\n"id": {\n      \t"type": "integer",\n      \t"format": "int32",\n      \t"minimum": 5,\n      \t"maximum": 50,\n      \t"exclusiveMinimum": false,\n      \t"exclusiveMaximum": false\n    \t},\n<\/code><\/pre>\n

The code above prevents that for an attribute <\/span>id<\/i><\/b> accept any integer smaller than 5 or larger than 50, as well as it says that it can’t be null or blank, as well as it comes with a standard regular expression for accepting an integer value. For the attribute <\/span>firstName<\/i><\/b>, it has a valid regular expression for a string that will act as the name, where the minimum number of characters accepted is 5 and the maximum is 30.<\/span><\/p>\n

 <\/p>\n

Best Practice #2: MIN\/MAX\/PATTERN in Parameters<\/h4>\n

For parameters inside the operations, we must have the same care we have with the schema, see the following code snippet:<\/span><\/p>\n

Code Definition<\/strong><\/p>\n

 @RequestMapping(method = RequestMethod.PATCH, path="\/person\/{id}", produces = MediaType.APPLICATION_JSON_VALUE)\n\u2026\npublic void updateEmail(\n   \t@ApiParam(required=true,  value="Id of the person to be updated. Cannot be empty.") @PathVariable  @Min(10) @Max(50) int id,\n   \t@ApiParam(required=true,  value="New Email - Cannot be empty.") @RequestParam  @Min(10) @Max(50) @Pattern(regexp= Constants.EMAIL_REGEX) String email)\n{\n   \tpersonService.getPersonById(id).setEmail(email);\n}<\/code><\/pre>\n

Swagger 2.0 Equivalent<\/strong><\/p>\n

 "parameters": [\n   {\n   \t"name": "email",\n   \t"in": "query",\n   \t"description": "New Email - Cannot be empty.",\n   \t"required": true,\n   \t"type": "string",\n   \t"maxLength": 50,\n   \t"minLength": 10,\n   \t"pattern": "^([a-zA-Z0-9_\\\\-\\\\.]+)@([a-zA-Z0-9_\\\\-\\\\.]+)\\\\.([a-zA-Z]{2,5})$",\n   \t"allowEmptyValue": false\n   },\n   {\n    \t"name": "id",\n    \t"in": "path",\n    \t "description": "Id of the person to be updated. Cannot be empty.",\n    \t "required": true,\n    \t "type": "integer",\n     \t"maximum": 50,\n     \t"exclusiveMaximum": false,\n     \t"minimum": 10,\n     \t"exclusiveMinimum": false,\n     \t"format": "int32"\n   }\n<\/code><\/pre>\n

The code snippet above prevents an attribute that expects an email address to receive a potential attack trying to use part of the valid domain, or even other tricks to violate this information. At the same time, the ID parameter is fully protected, working with values in the ranges and formats described in the generated OAS (Swagger) file.<\/p>\n

 <\/p>\n

Best Practice #3: ENSURES ALL ERROR CODES HAVE A CORRESPONDING SCHEMA<\/h4>\n

All error codes must have a corresponding error structure, described by a schema (this ensures we can validate payloads for requests\/responses).<\/span><\/p>\n

Depending on the verb used (GET, POST, PUT, etc.), we recommend supporting specific\u00a0 HTTP codes such as 401, 403, 404, or 415. Please see the code snippet below:\u00a0<\/span><\/p>\n

Code Definition<\/strong><\/p>\n

 @ApiResponses(value = {\n \t@ApiResponse(code = 200, message = "Successful operation", response = SuccessfulMessage.class),\n \t@ApiResponse(code = 401, message = "Requires Authentication", response = ErrorMessage.class),\n \t@ApiResponse(code = 403, message = "Not Authorized", response = ErrorMessage.class),\n \t@ApiResponse(code = 404, message = "User Not Found", response = ErrorMessage.class),\n \t@ApiResponse(code = 415, message = "Content type not supported.", response = ErrorMessage.class)})<\/code><\/pre>\n

Swagger 2.0 Equivalent<\/strong><\/p>\n

 "responses": {\n      \t"200": {\n        \t"description": "Successful operation",\n        \t"schema": {\n          \t"$ref": "#\/definitions\/SuccessfulMessage"\n        \t}\n      \t},\n      \t"401": {\n        \t"description": "Requires Authentication",\n        \t"schema": {\n          \t"$ref": "#\/definitions\/ErrorMessage"\n        \t}\n      \t},\n      \t"403": {\n        \t"description": "Not Authorized",\n        \t"schema": {\n        \t  "$ref": "#\/definitions\/ErrorMessage"\n        \t}\n      \t},\n      \t"404": {\n        \t"description": "User Not Found",\n        \t"schema": {\n          \t"$ref": "#\/definitions\/ErrorMessage"\n        \t}\n      \t},\n      \t"415": {\n \t       "description": "Content type not supported.",\n        \t"schema": {\n          \t"$ref": "#\/definitions\/ErrorMessage"\n        \t}\n      \t}\n<\/code><\/pre>\n

 <\/p>\n

Conclusion<\/b><\/h2>\n

Spring Boot is a widely used framework to produce APIs and Microservices, together with Springfox, both can deliver an impressive OAS (Swagger) file in terms of data validation at the same time that you can get your APIs fully protected. In order to get insightful recommendations to get better OAS (Swagger) files, please consider using our extensions for the main IDEs in the market (VS Code, IntelliJ, and Eclipse), as well as our extensions\/plugins for the CI\/CD (Jenkins, Gitlab, GitHub, Azure Pipelines, etc). Keep in mind that: The more secure OAS (Swagger) files are, the more secure your APIs will be.<\/span><\/p>\n

42Crunch IDE and CI\/CD Extensions: <\/span>https:\/\/42crunch.com\/free-tools\/<\/span><\/a><\/p>\n","protected":false},"excerpt":{"rendered":"

In the first part of this blog, we had covered the security aspects of Spring Boot Microservices and how to inject them into your code level to generate higher quality OAS (Swagger) files. In this second part, we will cover aspects regarding attributes, operations, and data. Data Validation for Secure APIs You must be aware […]<\/p>\n","protected":false},"author":12,"featured_media":11328,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_seopress_robots_primary_cat":"none","_seopress_titles_title":"API security aspects in Spring Boot and Spring Fox - Part 2.","_seopress_titles_desc":"In this second part, we will cover api security aspects regarding attributes, operations, and data in Spring Boot and Spring Fox.","_seopress_robots_index":"","site-sidebar-layout":"default","site-content-layout":"default","ast-site-content-layout":"","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"disabled","ast-hfb-above-header-display":"disabled","ast-hfb-below-header-display":"disabled","ast-hfb-mobile-header-display":"disabled","site-post-title":"disabled","ast-breadcrumbs-content":"disabled","ast-featured-img":"disabled","footer-sml-layout":"disabled","theme-transparent-header-meta":"default","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[6],"tags":[16],"class_list":["post-10086","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","tag-api-security-training"],"_links":{"self":[{"href":"https:\/\/staging2022.42crunch.com\/wp-json\/wp\/v2\/posts\/10086"}],"collection":[{"href":"https:\/\/staging2022.42crunch.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/staging2022.42crunch.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/staging2022.42crunch.com\/wp-json\/wp\/v2\/users\/12"}],"replies":[{"embeddable":true,"href":"https:\/\/staging2022.42crunch.com\/wp-json\/wp\/v2\/comments?post=10086"}],"version-history":[{"count":0,"href":"https:\/\/staging2022.42crunch.com\/wp-json\/wp\/v2\/posts\/10086\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/staging2022.42crunch.com\/wp-json\/wp\/v2\/media\/11328"}],"wp:attachment":[{"href":"https:\/\/staging2022.42crunch.com\/wp-json\/wp\/v2\/media?parent=10086"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/staging2022.42crunch.com\/wp-json\/wp\/v2\/categories?post=10086"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/staging2022.42crunch.com\/wp-json\/wp\/v2\/tags?post=10086"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}