How to Validate Request Headers in Spring Boot


In this article, we will see how to read request header in spring boot and How to validate request header in spring boot. In the rest web series, the information about the request body is sent through request header.These request headers are used for authentication and authorization of the rest web services. It also helps to get details about the data.

The request headers contains key value pair. It is a text data stored in key value format. Here we will see step by step procedure to how to configure request header in spring boot, how to read request header in spring boot and how to validate request header in spring boot.



Add dependency in pom.xml

The “spring-boot-starter-validation” dependency will include all the jars needed for the validation of the request header. The web application needs the dependence of “spring-boot-starter-browser.” This will allow the tomcat server and start as a web application. The default “spring-boot-starter-test” test dependency will be applied to pom.xml for the  unit testing.

If you have created a spring boot application, now you’re trying to incorporate the validation code, then add the “spring-boot-starter-validation” dependency to the pom.xml file. The complete pom.xml file will be as shown below.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.5.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.yawintutor</groupId>
	<artifactId>Spring-Application</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBootValidation</name>
	<description>Spring Boot Project</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-validation</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


How to read request headers in Spring Boot

The annotation @RequestHeader is used to map the request headers in spring boot application. The request headers are mapped with a java hash map. By iterating the map, all the headers can be read through the code. The request headers are stored in key value format.

TestController.java

package com.yawintutor;

import java.util.Map;

import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Validated
public class TestController {

	@PostMapping("/student/")
	ResponseEntity<String> student(@RequestHeader Map<String, String> headers) {
		headers.forEach((key, value) -> {
	        System.out.println("Header "+ key+" = "+ value);
	    });
		return ResponseEntity.ok("Headers are read successfully ");
	}
}

Output

Header content-type = application/json
Header cache-control = no-cache
Header postman-token = 396c92c9-849a-479f-91af-184d60d4fc45
Header user-agent = PostmanRuntime/7.1.1
Header accept = */*
Header host = localhost:8080
Header accept-encoding = gzip, deflate
Header content-length = 11
Header connection = keep-alive


How to Read a Request Header in Spring Boot

Spring boot supports to read a request header. The request headers are stored in a map, key value format. To get a request header, the map should be iterated. Spring boot allows to read a header without iterating the map. The code below shows how to read a request header without iterating the map in spring boot.

TestController.java

package com.yawintutor;

import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Validated
public class TestController {
	
	@PostMapping("/student/")
	ResponseEntity<String> student(@RequestHeader("content-length")  int value) {
	    System.out.println("Header content-length = "+ value);
		return ResponseEntity.ok("Headers are read successfully ");
	}
}

Output

Header content-length = 11


How to Read Optional Request Header in Spring Boot

The optional request header can be read using @RequestHeader annotation. Add required parameter in the annotation and set as false. If the optional request header is available, the value is printed. If not available, it is null.

package com.yawintutor;

import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Validated
public class TestController {
	
	@PostMapping("/student/")
	ResponseEntity<String> student(@RequestHeader(name="max-length", requried=false)  int value) {
	    System.out.println("Header max-length = "+ value);
		return ResponseEntity.ok("Headers are read successfully ");
	}
}

Output

Header max-length = null


How to Validate Request Header in Spring Boot

The spring boot allows to validate a request header as like other request parameters. The annotation @@Validated is used to validate the request header. In this example, the annotation @Min is used to check the min value

TestController.java

package com.yawintutor;

import javax.validation.constraints.Min;

import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Validated
public class TestController {
	
	@PostMapping("/student/")
	ResponseEntity<String> student(@RequestHeader("content-length") @Min(25) int value) {
	    System.out.println("Header content-length = "+ value);
		return ResponseEntity.ok("Headers are read successfully ");
	}
}


How to test validation

Run the below code in command prompt or import in postman.

curl -X POST \
  http://localhost:8080/student/ \
  -H 'Cache-Control: no-cache' \
  -H 'Content-Type: application/json' \
  -H 'Postman-Token: dc2ef549-1c71-417c-9873-d2bf2aaa3e58' \
  -d '{"age":"5"}'

Output

{
    "timestamp": "2020-03-27T05:14:50.195+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "student.value: must be greater than or equal to 25",
    "path": "/student/"
}



Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *