JsonValue performDynamicClientRegistration(
      final Context context,
      final JsonValue clientRegistrationConfiguration,
      final URI registrationEndpoint)
      throws RegistrationException {
    final Request request = new Request();
    request.setMethod("POST");
    request.setUri(registrationEndpoint);
    request.setEntity(clientRegistrationConfiguration.asMap());

    final Response response;
    try {
      response = blockingCall(registrationHandler, context, request);
    } catch (InterruptedException e) {
      throw new RegistrationException(
          format("Interrupted while waiting for '%s' response", request.getUri()), e);
    }
    if (!CREATED.equals(response.getStatus())) {
      throw new RegistrationException(
          "Cannot perform dynamic registration: this can be caused "
              + "by the distant server(busy, offline...) "
              + "or a malformed registration response.");
    }
    try {
      return getJsonContent(response);
    } catch (OAuth2ErrorException e) {
      throw new RegistrationException(
          "Cannot perform dynamic registration: invalid response JSON content.");
    }
  }
  @Test(enabled = true)
  public void shouldValidateRequestWhenAuthenticationFailed()
      throws ResourceException, AuthException {

    // Given
    MessageInfoContext messageInfo = mock(MessageInfoContext.class);
    AuthenticatorResult authResult = mock(AuthenticatorResult.class);
    Subject clientSubject = new Subject();
    Subject serviceSubject = new Subject();
    Map<String, Object> messageInfoMap = new HashMap<String, Object>();
    Map<String, Object> auditInfoMap = new HashMap<String, Object>();

    Request request = new Request();

    given(messageInfo.getRequest()).willReturn(request);
    request.getHeaders().put("X-OpenIDM-Username", "USERNAME");
    request.getHeaders().put("X-OpenIDM-Password", "PASSWORD");
    given(messageInfo.getRequestContextMap()).willReturn(messageInfoMap);
    messageInfoMap.put(AuditTrail.AUDIT_INFO_KEY, auditInfoMap);

    given(authResult.isAuthenticated()).willReturn(false);
    given(authenticator.authenticate(eq("USERNAME"), eq("PASSWORD"), Matchers.<Context>anyObject()))
        .willReturn(authResult);

    // When
    AuthStatus authStatus =
        module
            .validateRequest(messageInfo, clientSubject, serviceSubject)
            .getOrThrowUninterruptibly();

    // Then
    assertTrue(clientSubject.getPrincipals().isEmpty());
    assertEquals(authStatus, AuthStatus.SEND_FAILURE);
  }
  @Test
  public void shouldValidateRequestWhenUsernameHeaderIsEmptyString() throws AuthException {

    // Given
    MessageInfoContext messageInfo = mock(MessageInfoContext.class);
    Subject clientSubject = new Subject();
    Subject serviceSubject = new Subject();

    Request request = new Request();

    given(messageInfo.getRequest()).willReturn(request);
    request.getHeaders().put("X-OpenIDM-Username", "");
    request.getHeaders().put("X-OpenIDM-Password", "PASSWORD");

    // When
    AuthStatus authStatus =
        module
            .validateRequest(messageInfo, clientSubject, serviceSubject)
            .getOrThrowUninterruptibly();

    // Then
    verifyZeroInteractions(authenticator);
    assertTrue(clientSubject.getPrincipals().isEmpty());
    assertEquals(authStatus, AuthStatus.SEND_FAILURE);
  }
  @Test
  public void testHeadersAreRemoved() throws Exception {
    HttpBasicAuthFilter filter = new HttpBasicAuthFilter(null, null, failureHandler);
    filter.setCacheHeader(false);

    Exchange exchange = newExchange();
    Request request = newRequest();
    request.getHeaders().putSingle(AUTHORIZATION_HEADER, "Basic azerty");

    doAnswer(
            new Answer<Promise<Response, NeverThrowsException>>() {
              @Override
              public Promise<Response, NeverThrowsException> answer(
                  final InvocationOnMock invocation) throws Throwable {
                // Produce a valid response with an authentication challenge
                Response response = new Response();
                response.setStatus(Status.OK);
                response.getHeaders().putSingle(AUTHENTICATE_HEADER, "Realm toto");
                return Promises.newResultPromise(response);
              }
            })
        .when(terminalHandler)
        .handle(eq(exchange), argThat(new AbsenceOfHeaderInRequest(AUTHORIZATION_HEADER)));

    Response response = filter.filter(exchange, request, terminalHandler).getOrThrow();

    // Verify that the outgoing message has no authenticate header
    assertThat(response.getHeaders().get(AUTHENTICATE_HEADER)).isNull();
  }
    @Override
    public boolean matches(final Object o) {
      if (!(o instanceof Request)) {
        return false;
      }

      Request request = (Request) o;
      return request.getHeaders().get(headerName) == null;
    }
    @Override
    public Promise<Response, NeverThrowsException> answer(InvocationOnMock invocation)
        throws Throwable {
      Request request = (Request) invocation.getArguments()[1];

      // Verify the authorization header: base64(user:pass)
      assertThat(request.getHeaders().getFirst(AUTHORIZATION_HEADER))
          .isEqualTo("Basic " + credentials);

      // Produce a valid response, no special headers are required
      Response response = new Response();
      response.setStatus(Status.OK);
      return Promises.newResultPromise(response);
    }
  @Override
  protected Map<String, String> getContextsForAccessAttempt(Request request) {
    try {
      String jsonString = request.getEntity().getString();
      if (isNotEmpty(jsonString)) {
        JsonValue jsonValue = toJsonValue(jsonString);
        if (jsonValue.isDefined(AUTH_ID)) {
          populateContextFromAuthId(jsonValue.get(AUTH_ID).asString());
        }
      }
    } catch (IOException e) {
      // Do nothing
    }

    return super.getContextsForAccessAttempt(request);
  }
 private Request newRequest() throws Exception {
   Request request = new Request();
   request.setUri("http://openig.forgerock.org");
   return request;
 }