private byte[] readToken(HttpURLConnection conn)
      throws IOException, AuthenticationException {
    int status = conn.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK || status == HttpURLConnection.HTTP_UNAUTHORIZED) {
      String authHeader = conn.getHeaderField(WWW_AUTHENTICATE);
      if (authHeader == null) {
        authHeader = conn.getHeaderField(WWW_AUTHENTICATE.toLowerCase());
      }
      if (authHeader == null || !authHeader.trim().startsWith(NEGOTIATE)) {
        throw new AuthenticationException("Invalid SPNEGO sequence, '" + WWW_AUTHENTICATE +
                                          "' header incorrect: " + authHeader);
      }
      String negotiation = authHeader.trim().substring((NEGOTIATE + " ").length()).trim();
      return base64.decode(negotiation);
    }
    throw new AuthenticationException("Invalid SPNEGO sequence, status code: " + status);
  }
@Test(timeout = 60000)
  public void testReadToken() throws NoSuchMethodException, IOException, IllegalAccessException,
          InvocationTargetException {
    KerberosAuthenticator kerberosAuthenticator = new KerberosAuthenticator();
    FieldUtils.writeField(kerberosAuthenticator, "base64", new Base64(), true);

    Base64 base64 = new Base64();

    HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
    Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_UNAUTHORIZED);
    Mockito.when(conn.getHeaderField(KerberosAuthenticator.WWW_AUTHENTICATE))
            .thenReturn(KerberosAuthenticator.NEGOTIATE + " " +
                    Arrays.toString(base64.encode("foobar".getBytes())));

    Method method = KerberosAuthenticator.class.getDeclaredMethod("readToken",
            HttpURLConnection.class);
    method.setAccessible(true);

    method.invoke(kerberosAuthenticator, conn); // expecting this not to throw an exception
  }