CodeSV Blog!by CA Technologies, A Broadcom Company

Basic Authorization

How Can We Help?
< Back

[expand title=”Prerequisites” expanded=”true”]


Basic Authorization

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 = "";

  private static final String BODY = "Success";

  public VirtualServerRule vs = new VirtualServerRule();

  public void testBasicAuth() throws Exception {
    // Our service with basic authorization
        .matchesBasicAuthorization("commonUsername", "bestPasswordEver")
        .matchesBasicAuthorization(contains("common"), is("bestPasswordEver"))

    // Simulate 401 with Authentication header
                .withHeader("WWW-Authenticate", "Basic")

    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials
        = new UsernamePasswordCredentials("commonUsername", "bestPasswordEver");
    provider.setCredentials(AuthScope.ANY, credentials);

    HttpClient client = HttpClientBuilder.create()

    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) {

    String body = result.toString();
    assertEquals(200, response.getStatusLine().getStatusCode());
    assertEquals(BODY, body);

For a complete example see: BasicAuthExample

Previous URL Parameters
Next Encoding
Table of Contents

Comments are currently closed.