Search in sources :

Example 1 with RestAuthResponseException

use of org.forgerock.openam.core.rest.authn.exceptions.RestAuthResponseException in project OpenAM by OpenRock.

the class AuthenticationServiceV1 method authenticate.

/**
     * Handles both initial and subsequent RESTful calls from clients submitting Callbacks for the authentication
     * process to continue. This is determined by checking if the POST body is empty or not. If it is empty then this
     * is initiating the authentication process otherwise it is a subsequent call submitting Callbacks.
     *
     * Initiating authentication request using the query parameters from the URL starts the login process and either
     * returns an SSOToken on successful authentication or a number of Callbacks needing to be completed before
     * authentication can proceed or an exception if any problems occurred whilst trying to authenticate.
     *
     * Using the body of the POST request the method continues the login process, submitting the given Callbacks and
     * then either returns an SSOToken on successful authentication or a number of additional Callbacks needing to be
     * completed before authentication can proceed or an exception if any problems occurred whilst trying to
     * authenticate.
     *
     * @param context The request context.
     * @param httpRequest The HTTP request.
     * @return A Json Representation of the response body. The response will contain either a JSON object containing the
     * SSOToken id from a successful authentication, a JSON object containing a number of Callbacks for the client to
     * complete and return or a JSON object containing an exception message.
     * @throws ResourceException If there is an error processing the authentication request.
     */
@Post
public Response authenticate(@Contextual Context context, @Contextual Request httpRequest) {
    if (!isSupportedMediaType(httpRequest)) {
        if (DEBUG.errorEnabled()) {
            DEBUG.error("AuthenticationService :: Unable to handle media type request : " + ContentTypeHeader.valueOf(httpRequest).getType());
        }
        return handleErrorResponse(httpRequest, Status.UNSUPPORTED_MEDIA_TYPE, null);
    }
    final HttpServletResponse response = getHttpServletResponse(context);
    Form urlQueryString = getUrlQueryString(httpRequest);
    final String sessionUpgradeSSOTokenId = urlQueryString.getFirst("sessionUpgradeSSOTokenId");
    try {
        JsonValue jsonContent;
        try {
            jsonContent = getJsonContent(httpRequest);
        } catch (IOException e) {
            DEBUG.message("AuthenticationService.authenticate() :: JSON parsing error", e);
            return handleErrorResponse(httpRequest, Status.BAD_REQUEST, e);
        }
        final HttpServletRequest request = getHttpServletRequest(context, jsonContent);
        JsonValue jsonResponse;
        if (jsonContent != null && jsonContent.size() > 0) {
            // submit requirements
            jsonResponse = restAuthenticationHandler.continueAuthentication(request, response, jsonContent, sessionUpgradeSSOTokenId);
        } else {
            // initiate
            final String authIndexType = urlQueryString.getFirst("authIndexType");
            final String authIndexValue = urlQueryString.getFirst("authIndexValue");
            jsonResponse = restAuthenticationHandler.initiateAuthentication(request, response, authIndexType, authIndexValue, sessionUpgradeSSOTokenId);
        }
        return createResponse(jsonResponse);
    } catch (RestAuthResponseException e) {
        DEBUG.message("AuthenticationService.authenticate() :: Exception from CallbackHandler", e);
        return handleErrorResponse(httpRequest, Status.valueOf(e.getStatusCode()), e);
    } catch (RestAuthException e) {
        DEBUG.message("AuthenticationService.authenticate() :: Rest Authentication Exception", e);
        return handleErrorResponse(httpRequest, Status.valueOf(e.getStatusCode()), e);
    } catch (IOException e) {
        DEBUG.error("AuthenticationService.authenticate() :: Internal Error", e);
        return handleErrorResponse(httpRequest, Status.INTERNAL_SERVER_ERROR, e);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) RestAuthException(org.forgerock.openam.core.rest.authn.exceptions.RestAuthException) Form(org.forgerock.http.protocol.Form) RestAuthResponseException(org.forgerock.openam.core.rest.authn.exceptions.RestAuthResponseException) JsonValue(org.forgerock.json.JsonValue) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Post(org.forgerock.openam.http.annotations.Post)

Example 2 with RestAuthResponseException

use of org.forgerock.openam.core.rest.authn.exceptions.RestAuthResponseException in project OpenAM by OpenRock.

the class AuthenticationServiceV2Test method shouldReturnUnauthorizedCodeWithJsonFailureMessage.

@Test
public void shouldReturnUnauthorizedCodeWithJsonFailureMessage() throws IOException {
    // given
    Request httpRequest = new Request();
    JsonValue jsonValue = json(object(field("failure", true), field("reason", "http-auth-failed"), field("authId", "12345")));
    RestAuthResponseException exception = new RestAuthResponseException(RestAuthException.UNAUTHORIZED, Collections.<String, String>emptyMap(), jsonValue);
    // when
    Response response = authServiceV2.handleErrorResponse(httpRequest, Status.valueOf(exception.getStatusCode()), exception);
    // then
    assertThat(response.getStatus()).isEqualToComparingFieldByField(Status.UNAUTHORIZED);
    JsonValue responseBody = json(response.getEntity().getJson());
    assertThat(responseBody).booleanAt("failure").isTrue();
    assertThat(responseBody).stringAt("reason").isEqualTo("http-auth-failed");
    assertThat(responseBody).stringAt("authId").isEqualTo("12345");
}
Also used : Response(org.forgerock.http.protocol.Response) RestAuthResponseException(org.forgerock.openam.core.rest.authn.exceptions.RestAuthResponseException) Request(org.forgerock.http.protocol.Request) JsonValue(org.forgerock.json.JsonValue) Test(org.testng.annotations.Test)

Example 3 with RestAuthResponseException

use of org.forgerock.openam.core.rest.authn.exceptions.RestAuthResponseException in project OpenAM by OpenRock.

the class AuthenticationServiceV1Test method shouldReturnUnauthorizedCodeWithJsonFailureMessage.

@Test
public void shouldReturnUnauthorizedCodeWithJsonFailureMessage() throws IOException {
    // given
    Request httpRequest = new Request();
    JsonValue jsonValue = json(object(field("failure", true), field("reason", "http-auth-failed"), field("authId", "12345")));
    RestAuthResponseException exception = new RestAuthResponseException(RestAuthException.UNAUTHORIZED, Collections.<String, String>emptyMap(), jsonValue);
    // when
    Response response = authServiceV1.handleErrorResponse(httpRequest, Status.valueOf(exception.getStatusCode()), exception);
    // then
    assertThat(response.getStatus()).isEqualToComparingFieldByField(Status.UNAUTHORIZED);
    JsonValue responseBody = json(response.getEntity().getJson());
    assertThat(responseBody).booleanAt("failure").isTrue();
    assertThat(responseBody).stringAt("reason").isEqualTo("http-auth-failed");
    assertThat(responseBody).stringAt("authId").isEqualTo("12345");
}
Also used : Response(org.forgerock.http.protocol.Response) RestAuthResponseException(org.forgerock.openam.core.rest.authn.exceptions.RestAuthResponseException) Request(org.forgerock.http.protocol.Request) JsonValue(org.forgerock.json.JsonValue) Test(org.testng.annotations.Test)

Example 4 with RestAuthResponseException

use of org.forgerock.openam.core.rest.authn.exceptions.RestAuthResponseException in project OpenAM by OpenRock.

the class RestAuthenticationHandlerTest method shouldInitiateAuthenticationViaGET4.

@Test
public void shouldInitiateAuthenticationViaGET4() throws AuthLoginException, L10NMessageImpl, JSONException, IOException, RestAuthResponseException, SignatureException, RestAuthException {
    //Given
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse httpResponse = mock(HttpServletResponse.class);
    String authIndexType = null;
    String indexValue = null;
    String sessionUpgradeSSOTokenId = null;
    Callback[] callbacks = new Callback[0];
    AuthContextLocalWrapper authContextLocalWrapper = mock(AuthContextLocalWrapper.class);
    LoginProcess loginProcess = mock(LoginProcess.class);
    given(loginProcess.getLoginStage()).willReturn(LoginStage.REQUIREMENTS_WAITING);
    given(loginProcess.getCallbacks()).willReturn(callbacks);
    given(loginProcess.getAuthContext()).willReturn(authContextLocalWrapper);
    PagePropertiesCallback pagePropertiesCallback = mock(PagePropertiesCallback.class);
    given(pagePropertiesCallback.getTemplateName()).willReturn("TEMPLATE_NAME");
    given(pagePropertiesCallback.getModuleName()).willReturn("MODULE_NAME");
    given(pagePropertiesCallback.getPageState()).willReturn("PAGE_STATE");
    JsonValue jsonCallbacks = new JsonValue(new HashMap<String, Object>());
    jsonCallbacks.add("KEY", "VALUE");
    Map<String, String> responseHeaders = new HashMap<String, String>();
    responseHeaders.put("HEADER_KEY", "HEADER_VALUE");
    JsonValue jsonResponse = new JsonValue(new HashMap<String, Object>());
    jsonResponse.add("KEY", "VALUE");
    RestAuthResponseException restAuthResponseException = new RestAuthResponseException(999, responseHeaders, jsonResponse);
    given(loginAuthenticator.getLoginProcess(Matchers.<LoginConfiguration>anyObject())).willReturn(loginProcess);
    given(restAuthCallbackHandlerManager.handleCallbacks(request, httpResponse, callbacks)).willThrow(restAuthResponseException);
    given(authIdHelper.createAuthId(Matchers.<LoginConfiguration>anyObject(), eq(authContextLocalWrapper))).willReturn("AUTH_ID");
    //When
    try {
        restAuthenticationHandler.initiateAuthentication(request, httpResponse, authIndexType, indexValue, sessionUpgradeSSOTokenId);
    } catch (RestAuthResponseException e) {
        JsonValue response = e.getJsonResponse();
        assertEquals(response.size(), 2);
        assertEquals(response.get("authId").asString(), "AUTH_ID");
        assertEquals(response.get("KEY").asString(), "VALUE");
        Map<String, String> headers = e.getResponseHeaders();
        assertEquals(headers.get("HEADER_KEY"), "HEADER_VALUE");
        assertEquals(e.getStatusCode(), 999);
        return;
    }
    //Then
    fail();
}
Also used : PagePropertiesCallback(com.sun.identity.authentication.spi.PagePropertiesCallback) HashMap(java.util.HashMap) JsonValue(org.forgerock.json.JsonValue) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthContextLocalWrapper(org.forgerock.openam.core.rest.authn.core.wrappers.AuthContextLocalWrapper) LoginProcess(org.forgerock.openam.core.rest.authn.core.LoginProcess) HttpServletRequest(javax.servlet.http.HttpServletRequest) PagePropertiesCallback(com.sun.identity.authentication.spi.PagePropertiesCallback) Callback(javax.security.auth.callback.Callback) RestAuthResponseException(org.forgerock.openam.core.rest.authn.exceptions.RestAuthResponseException) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.testng.annotations.Test)

Example 5 with RestAuthResponseException

use of org.forgerock.openam.core.rest.authn.exceptions.RestAuthResponseException in project OpenAM by OpenRock.

the class RestAuthHttpCallbackHandlerTest method shouldFailToUpdateCallbackFromRequestWhenHttpAuthorizationIsNull.

@Test
public void shouldFailToUpdateCallbackFromRequestWhenHttpAuthorizationIsNull() throws RestAuthResponseException, RestAuthException {
    //Given
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    HttpCallback httpCallback = mock(HttpCallback.class);
    given(request.getParameter("httpAuthorization")).willReturn(null);
    given(httpCallback.getNegotiationHeaderName()).willReturn("WWW-Authenticate");
    given(httpCallback.getNegotiationHeaderValue()).willReturn("Negotiate");
    //When
    boolean exceptionCaught = false;
    RestAuthResponseException exception = null;
    try {
        restAuthHttpCallbackHandler.updateCallbackFromRequest(request, response, httpCallback);
    } catch (RestAuthResponseException e) {
        exceptionCaught = true;
        exception = e;
    }
    //Then
    assertTrue(exceptionCaught);
    assertEquals(exception.getStatusCode(), 401);
    assertEquals(exception.getResponseHeaders().size(), 1);
    assertTrue(exception.getResponseHeaders().containsKey("WWW-Authenticate"));
    assertTrue(exception.getResponseHeaders().containsValue("Negotiate"));
    assertEquals(exception.getJsonResponse().get("failure").asBoolean(), (Boolean) true);
    assertEquals(exception.getJsonResponse().get("reason").asString(), "http-auth-failed");
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) RestAuthResponseException(org.forgerock.openam.core.rest.authn.exceptions.RestAuthResponseException) HttpCallback(com.sun.identity.authentication.spi.HttpCallback) HttpServletResponse(javax.servlet.http.HttpServletResponse) Test(org.testng.annotations.Test)

Aggregations

RestAuthResponseException (org.forgerock.openam.core.rest.authn.exceptions.RestAuthResponseException)10 JsonValue (org.forgerock.json.JsonValue)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)5 Test (org.testng.annotations.Test)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 Response (org.forgerock.http.protocol.Response)4 RestAuthException (org.forgerock.openam.core.rest.authn.exceptions.RestAuthException)4 HashMap (java.util.HashMap)3 Map (java.util.Map)3 HttpCallback (com.sun.identity.authentication.spi.HttpCallback)2 Request (org.forgerock.http.protocol.Request)2 SSOToken (com.iplanet.sso.SSOToken)1 PagePropertiesCallback (com.sun.identity.authentication.spi.PagePropertiesCallback)1 RedirectCallback (com.sun.identity.authentication.spi.RedirectCallback)1 IOException (java.io.IOException)1 Callback (javax.security.auth.callback.Callback)1 Form (org.forgerock.http.protocol.Form)1 ResourceException (org.forgerock.json.resource.ResourceException)1 AuthenticationContext (org.forgerock.openam.core.rest.authn.core.AuthenticationContext)1 LoginProcess (org.forgerock.openam.core.rest.authn.core.LoginProcess)1