-
Notifications
You must be signed in to change notification settings - Fork 12
Basic Authorization
Prerequisite
CodeSV supports matching basic authorization requests with predefined methods. It is possible to directly match the username and password or use different matchers to do more complex assertions. You can combine more than one virtualized service to create more complex use cases as shown in the example below.
It is also important to note that we use forAnyRequest()
static method to define the default response for any request that is not matched by the other virtualized services. We use this functionality to return the unauthorized response message with status code 401
and a special header WWW-Authenticate
set to Basic
to tell the HTTP client to use basic authorization.
Basic authorization example:
private static final String URL = "http://www.ca.com/portfolio";
private static final String BODY = "Success";
@Rule
public VirtualServerRule vs = new VirtualServerRule();
@Test
public void testBasicAuth() throws Exception {
// Our service with basic authorization
forGet(URL)
.matchesBasicAuthorization("commonUsername", "bestPasswordEver")
.matchesBasicAuthorization(contains("common"), is("bestPasswordEver"))
.doReturn(
okMessage()
.withStringBody(BODY)
);
// Simulate 401 with Authentication header
forAnyRequest(URL)
.doReturn(
unauthorizedMessage()
.withHeader("WWW-Authenticate", "Basic")
);
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials
= new UsernamePasswordCredentials("commonUsername", "bestPasswordEver");
provider.setCredentials(AuthScope.ANY, credentials);
HttpClient client = HttpClientBuilder.create()
.setDefaultCredentialsProvider(provider)
.build();
HttpGet request = new HttpGet(URL);
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
String body = result.toString();
assertEquals(200, response.getStatusLine().getStatusCode());
assertNotNull(body);
assertEquals(BODY, body);
}
For a complete example see: BasicAuthExample