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) OR @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
There are different ways that can be used to perform Basic Authentication with TestRestTemplate.
- Authentication headers
- ‘withBasicAuth’ method
- 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.