Spring Boot Test and Spring Security: Perform Http Basic Authentication with TestRestTemplate


What is HTTP Basic Authentication?

If you want to refresh your knowledge on HTTP Basic Authentication, please click here to refer my article on that.

Here i am going to show you how to execute spring test cases on REST endpoints that are secured with Spring Security and required HTTP Basic Authentication.  Here we are going to use the TestRestTemplate as the REST client for invoking REST endpoints.



TestRestTemplate is a convenience alternative to Spring’s RestTemplate that is useful in integration tests. If you use the @SpringBoootTest annotation , with one of the following webEnviroment attribute, you can use fully configured TestRestTemplate in your Test class.

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)


There are different ways that can be used to perform Basic Authentication with TestRestTemplate.

  1.  Authentication headers
  2.  ‘withBasicAuth’ method
  3.  With Authenticated TestRestTemplate object.

Lets look at each of those approaches in detailed as follows.

1. Authentication headers

In this approach, authentication string is added and sent in the HTTP request header (Authorization header and Basic Scheme).

e.g:- Authorization Basic xxxxxxx


In here xxxxxxx is in the following format.



In the following code segment you can see that authentication string is added in HTTP request header.




2. ‘withBasicAuth’ method

TestRestTemplate gives us a method withBasicAuth() which can be used to add credentials to an already existing template






3.  With Authenticated TestRestTemplate object.

TestRestTemplate can be created with providing login credentials. Then it can be used to access the secured REST endpoints.




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s