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.
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.
base64encoded(username:password)
In the following code segment you can see that authentication string is added in HTTP request header.
public FindUserResponse findUserById() | |
{ | |
String username = "chathuranga"; | |
String password = "123"; | |
Integer userId = 1; | |
String url = "http://localhost:" + port + "/users/" + userId; | |
String authorizationHeader = "Basic " + DatatypeConverter.printBase64Binary((username + ":" + password).getBytes()); | |
HttpHeaders requestHeaders = new HttpHeaders(); | |
requestHeaders.setContentType(MediaType.APPLICATION_JSON); | |
requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); | |
requestHeaders.add("Authorization", authorizationHeader); | |
//fields are empty | |
AddUserRequest addUserRequest = new AddUserRequest(); | |
HttpEntity<AddUserRequest> requestEntity = new HttpEntity<>(addUserRequest, requestHeaders); | |
ResponseEntity<FindUserResponse> responseEntity = testRestTemplate.exchange( | |
url, | |
HttpMethod.GET, | |
requestEntity, | |
FindUserResponse.class | |
); | |
FindUserResponse findUserResponse = responseEntity.getBody(); | |
return findUserResponse; | |
} |
2. ‘withBasicAuth’ method
TestRestTemplate gives us a method withBasicAuth() which can be used to add credentials to an already existing template
public void creatUser() | |
{ | |
String url = "http://localhost:" + port + "/users"; | |
String username = "chathuranga"; | |
String password = "123"; | |
HttpHeaders requestHeaders = new HttpHeaders(); | |
requestHeaders.setContentType(MediaType.APPLICATION_JSON); | |
requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); | |
AddUserRequest addUserRequest = new AddUserRequest(); | |
addUserRequest.setName("Sample User"); | |
addUserRequest.setUsername("user1"); | |
addUserRequest.setPassword("pass123"); | |
HttpEntity<AddUserRequest> requestEntity = new HttpEntity<>(addUserRequest, requestHeaders); | |
//basic authentication is made with 'withBasicAuth' method available in the TestRestTemplate | |
ResponseEntity<AddUserResponse> responseEntity = testRestTemplate.withBasicAuth(username, password) | |
.exchange( | |
url, | |
HttpMethod.POST, | |
requestEntity, | |
AddUserResponse.class | |
); | |
if (responseEntity.getStatusCode() == HttpStatus.OK) | |
{ | |
AddUserResponse addUserResponse = responseEntity.getBody(); | |
System.out.println(addUserResponse); | |
} | |
} |
3. With Authenticated TestRestTemplate object.
TestRestTemplate can be created with providing login credentials. Then it can be used to access the secured REST endpoints.
@Test | |
public void testFindUserById4() { | |
String username = "chathuranga"; | |
String password = "123"; | |
Integer userId = 200; | |
String url = "http://localhost:" + port + "/users/" + userId; | |
HttpHeaders requestHeaders = new HttpHeaders(); | |
requestHeaders.setContentType(MediaType.APPLICATION_JSON); | |
requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); | |
HttpEntity<AddUserRequest> requestEntity = new HttpEntity<>(requestHeaders); | |
TestRestTemplate testRestTemplate1 = new TestRestTemplate(username, password, TestRestTemplate.HttpClientOption.ENABLE_COOKIES); | |
ResponseEntity<FindUserResponse> responseEntity = testRestTemplate1.exchange( | |
url, | |
HttpMethod.GET, | |
requestEntity, | |
FindUserResponse.class | |
); | |
assertNotNull(responseEntity); | |
assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); | |
} |