Search in sources :

Example 6 with RestAuthResponseException

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

the class RestAuthHttpCallbackHandlerTest method shouldFailToUpdateCallbackFromRequestWhenHttpAuthorizationIsEmptyString.

@Test
public void shouldFailToUpdateCallbackFromRequestWhenHttpAuthorizationIsEmptyString() throws RestAuthResponseException, RestAuthException {
    //Given
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    HttpCallback httpCallback = mock(HttpCallback.class);
    given(request.getParameter("httpAuthorization")).willReturn("");
    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)

Example 7 with RestAuthResponseException

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

the class AuthenticationServiceV1 method handleErrorResponse.

/**
     * Processes the given Exception into a Restlet response representation or wrap it into
     * a ResourceException, which will be thrown.
     *
     * @param status The status to set the response to.
     * @param exception The Exception to be handled.
     * @return The Restlet Response Representation.
     * @throws ResourceException If the given exception is wrapped in a ResourceException.
     */
protected Response handleErrorResponse(Request request, Status status, Exception exception) {
    Reject.ifNull(status);
    Response response = new Response(status);
    final Map<String, Object> rep = new HashMap<>();
    if (exception instanceof RestAuthResponseException) {
        final RestAuthResponseException authResponseException = (RestAuthResponseException) exception;
        for (Map.Entry<String, String> entry : authResponseException.getResponseHeaders().entrySet()) {
            response.getHeaders().put(entry.getKey(), entry.getValue());
        }
        rep.putAll(authResponseException.getJsonResponse().asMap());
    } else if (exception instanceof RestAuthException) {
        final RestAuthException authException = (RestAuthException) exception;
        if (authException.getFailureUrl() != null) {
            rep.put("failureUrl", authException.getFailureUrl());
        }
        rep.put("errorMessage", getLocalizedMessage(request, exception));
    } else if (exception == null) {
        rep.put("errorMessage", status.getReasonPhrase());
    } else {
        rep.put("errorMessage", getLocalizedMessage(request, exception));
    }
    response.setEntity(rep);
    return response;
}
Also used : Response(org.forgerock.http.protocol.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) RestAuthException(org.forgerock.openam.core.rest.authn.exceptions.RestAuthException) HashMap(java.util.HashMap) RestAuthResponseException(org.forgerock.openam.core.rest.authn.exceptions.RestAuthResponseException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 8 with RestAuthResponseException

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

the class AuthenticationServiceV2 method handleErrorResponse.

@Override
protected Response handleErrorResponse(Request request, Status status, Exception exception) {
    Reject.ifNull(status);
    Response response = new Response(status);
    if (exception instanceof RestAuthResponseException) {
        final RestAuthResponseException authResponseException = (RestAuthResponseException) exception;
        for (Map.Entry<String, String> entry : authResponseException.getResponseHeaders().entrySet()) {
            response.getHeaders().add(entry.getKey(), entry.getValue());
        }
        response.setEntity(authResponseException.getJsonResponse().asMap());
        return response;
    } else if (exception instanceof RestAuthException) {
        final RestAuthException rae = (RestAuthException) exception;
        ResourceException cause = ResourceException.getException(rae.getStatusCode(), getLocalizedMessage(request, rae));
        if (rae.getFailureUrl() != null) {
            cause.setDetail(json(object(field("failureUrl", rae.getFailureUrl()))));
        }
        return createExceptionResponse(response, cause);
    } else if (exception == null) {
        return createExceptionResponse(response, ResourceException.getException(status.getCode()));
    } else {
        return createExceptionResponse(response, ResourceException.getException(status.getCode(), exception.getMessage(), exception));
    }
}
Also used : Response(org.forgerock.http.protocol.Response) RestAuthException(org.forgerock.openam.core.rest.authn.exceptions.RestAuthException) RestAuthResponseException(org.forgerock.openam.core.rest.authn.exceptions.RestAuthResponseException) ResourceException(org.forgerock.json.resource.ResourceException) Map(java.util.Map)

Example 9 with RestAuthResponseException

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

the class RestAuthHttpCallbackHandler method updateCallbackFromRequest.

/**
     * Checks the request for the presence of a header with the Authorization Header as define in the HttpCallBack,
     * if present and not an empty string then sets this on the Callback and returns true. Otherwise does nothing and
     * returns false.
     *
     * {@inheritDoc}
     */
public boolean updateCallbackFromRequest(HttpServletRequest request, HttpServletResponse response, HttpCallback callback) throws RestAuthResponseException {
    String httpAuthorization = request.getHeader(callback.getAuthorizationHeader());
    if (httpAuthorization == null || "".equals(httpAuthorization)) {
        DEBUG.message("Authorization Header not set in request.");
        JsonValue jsonValue = JsonValueBuilder.jsonValue().put("failure", true).put("reason", HTTP_AUTH_FAILED).build();
        Map<String, String> responseHeaders = new HashMap<String, String>();
        responseHeaders.put(callback.getNegotiationHeaderName(), callback.getNegotiationHeaderValue());
        throw new RestAuthResponseException(RestAuthException.UNAUTHORIZED, responseHeaders, jsonValue);
    }
    callback.setAuthorization(httpAuthorization);
    return true;
}
Also used : HashMap(java.util.HashMap) RestAuthResponseException(org.forgerock.openam.core.rest.authn.exceptions.RestAuthResponseException) JsonValue(org.forgerock.json.JsonValue)

Example 10 with RestAuthResponseException

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

the class RestAuthenticationHandler method processAuthentication.

/**
     * Using the given LoginProcess will process the authentication by getting the required callbacks and either
     * completing and submitting them or sending the requirements back to the client as JSON. If the authentication
     * process has completed it will then check the completion status and will either return an error or the SSO Token
     * Id to the client.
     *
     * @param request The HttpServletRequest.
     * @param response The HttpServletResponse.
     * @param postBody The post body of the request.
     * @param loginProcess The LoginProcess used to track the login.
     * @param loginConfiguration The LoginConfiguration used to configure the login process.
     * @return A ResponseBuilder which contains the contents of the response to return to the client.
     * @throws AuthLoginException If there is a problem submitting the callbacks.
     * @throws SignatureException If there is a problem creating the JWT to use in the response to the client.
     */
private JsonValue processAuthentication(HttpServletRequest request, HttpServletResponse response, JsonValue postBody, String authId, LoginProcess loginProcess, LoginConfiguration loginConfiguration) throws AuthLoginException, SignatureException, RestAuthException {
    switch(loginProcess.getLoginStage()) {
        case REQUIREMENTS_WAITING:
            {
                Callback[] callbacks = loginProcess.getCallbacks();
                JsonValue jsonCallbacks;
                try {
                    if (callbacks.length == 1 && callbacks[0] instanceof RedirectCallback && postBody != null) {
                        jsonCallbacks = null;
                    } else {
                        jsonCallbacks = handleCallbacks(request, response, postBody, callbacks);
                    }
                } catch (RestAuthResponseException e) {
                    // Include the authId in the JSON response.
                    if (authId == null) {
                        authId = authIdHelper.createAuthId(loginConfiguration, loginProcess.getAuthContext());
                    }
                    e.getJsonResponse().put(AUTH_ID, authId);
                    AuditRequestContext.putProperty(AUTH_ID, authId);
                    throw e;
                }
                if (jsonCallbacks != null && jsonCallbacks.size() > 0) {
                    JsonValue jsonValue = createJsonCallbackResponse(authId, loginConfiguration, loginProcess, jsonCallbacks);
                    return jsonValue;
                } else {
                    loginProcess = loginProcess.next(callbacks);
                    return processAuthentication(request, response, null, authId, loginProcess, loginConfiguration);
                }
            }
        case COMPLETE:
            {
                loginProcess.cleanup();
                if (loginProcess.isSuccessful()) {
                    // send token to client
                    JsonObject jsonResponseObject = JsonValueBuilder.jsonValue();
                    SSOToken ssoToken = loginProcess.getSSOToken();
                    if (ssoToken != null) {
                        String tokenId = ssoToken.getTokenID().toString();
                        jsonResponseObject.put(TOKEN_ID, tokenId);
                        AuditRequestContext.putProperty(TOKEN_ID, tokenId);
                    } else {
                        jsonResponseObject.put("message", "Authentication Successful");
                    }
                    String gotoUrl = urlValidator.getRedirectUrl(loginProcess.getOrgDN(), urlValidator.getValueFromJson(postBody, RedirectUrlValidator.GOTO), loginProcess.getSuccessURL());
                    jsonResponseObject.put("successUrl", gotoUrl);
                    return jsonResponseObject.build();
                } else {
                    // send Error to client
                    AuthenticationContext authContext = loginProcess.getAuthContext();
                    String errorCode = authContext.getErrorCode();
                    String errorMessage = authContext.getErrorMessage();
                    throw new RestAuthErrorCodeException(errorCode, errorMessage);
                }
            }
    }
    // This should never happen
    throw new RestAuthException(ResourceException.INTERNAL_ERROR, "Unknown Authentication State!");
}
Also used : RestAuthErrorCodeException(org.forgerock.openam.core.rest.authn.exceptions.RestAuthErrorCodeException) RestAuthException(org.forgerock.openam.core.rest.authn.exceptions.RestAuthException) RedirectCallback(com.sun.identity.authentication.spi.RedirectCallback) SSOToken(com.iplanet.sso.SSOToken) AuthenticationContext(org.forgerock.openam.core.rest.authn.core.AuthenticationContext) RestAuthResponseException(org.forgerock.openam.core.rest.authn.exceptions.RestAuthResponseException) JsonValue(org.forgerock.json.JsonValue) JsonObject(org.forgerock.openam.utils.JsonObject)

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