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
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.