Java Code Examples for io.vertx.reactivex.ext.web.RoutingContext#request()

The following examples show how to use io.vertx.reactivex.ext.web.RoutingContext#request() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ErrorHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private void handleException(RoutingContext routingContext, String errorCode, String errorDetail) {
    try {
        final HttpServerRequest request = routingContext.request();
        // prepare query parameters
        Map<String, String> parameters = new LinkedHashMap<>();
        // get client if exists
        Client client = routingContext.get(CLIENT_CONTEXT_KEY);
        if (client != null) {
            parameters.put(Parameters.CLIENT_ID, client.getClientId());
        } else if (request.getParam(Parameters.CLIENT_ID) != null) {
            parameters.put(Parameters.CLIENT_ID, (request.getParam(Parameters.CLIENT_ID)));
        }
        // append error information
        parameters.put("error", errorCode);
        if (errorDetail != null) {
            parameters.put("error_description", errorDetail);
        }
        // redirect
        String proxiedErrorPage = UriBuilderRequest.resolveProxyRequest(request,  errorPage, parameters, true);
        doRedirect(routingContext.response(), proxiedErrorPage);
    } catch (Exception e) {
        logger.error("Unable to handle root error response", e);
        doRedirect(routingContext.response(),  errorPage);
    }
}
 
Example 2
Source File: LoginErrorHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    final HttpServerRequest request = context.request();
    final String error = request.getParam(ERROR_PARAM);
    final String errorCode = request.getParam(ERROR_CODE_PARAM);
    final String errorDescription = request.getParam(ERROR_DESCRIPTION_PARAM);

    // no error to handle, continue
    if (error == null) {
        context.next();
        return;
    }

    // put error data in context
    Map<String, Object> errorContext = new HashMap<>();
    errorContext.put(ERROR_CODE_CONTEXT_KEY, errorCode);
    errorContext.put(ERROR_DESCRIPTION_CONTEXT_KEY, errorDescription);
    context.put(ERROR_CONTEXT_KEY, errorContext);
    context.next();
}
 
Example 3
Source File: ForgotPasswordEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    final HttpServerRequest request = routingContext.request();
    final String error = request.getParam(ERROR_PARAM);
    final String success = request.getParam(SUCCESS_PARAM);
    final String warning = request.getParam(WARNING_PARAM);
    final Client client = routingContext.get("client");
    // add query params to context
    routingContext.put(ERROR_PARAM, error);
    routingContext.put(SUCCESS_PARAM, success);
    routingContext.put(WARNING_PARAM, warning);
    routingContext.put(PARAM_CONTEXT_KEY, Collections.singletonMap(Parameters.CLIENT_ID, request.getParam(Parameters.CLIENT_ID)));

    // render the forgot password page
    engine.render(routingContext.data(), getTemplateFileName(client), res -> {
        if (res.succeeded()) {
            routingContext.response().putHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML);
            routingContext.response().end(res.result());
        } else {
            logger.error("Unable to render forgot password page", res.cause());
            routingContext.fail(res.cause());
        }
    });
}
 
Example 4
Source File: RedirectHandlerImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    try {
        final HttpServerRequest request = routingContext.request();
        final Map<String, String> requestParameters = request.params().entries().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        String proxiedRedirectURI = UriBuilderRequest.resolveProxyRequest(routingContext.request(), redirectURL, requestParameters, true);
        routingContext.response()
                .putHeader(HttpHeaders.LOCATION, proxiedRedirectURI)
                .setStatusCode(302)
                .end();
    } catch (Exception e) {
        logger.warn("Failed to decode login redirect url", e);
        routingContext.response()
                .putHeader(HttpHeaders.LOCATION, redirectURL)
                .setStatusCode(302)
                .end();
    }
}
 
Example 5
Source File: ErrorEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    final HttpServerRequest request = routingContext.request();
    final String clientId = request.getParam(Parameters.CLIENT_ID);

    if (clientId == null) {
        renderErrorPage(routingContext, null);
        return;
    }

    // fetch client to display its own custom page
    resolveClient(clientId, handler -> {
        if (handler.failed()) {
            // an error occurs while fetching the client
            // we will display the domain error page
            // log this error for the prosperity
            logger.debug("An error occurs while fetching client {}", clientId, handler.cause());
            renderErrorPage(routingContext, null);
            return;
        }

        renderErrorPage(routingContext, handler.result());
    });
}
 
Example 6
Source File: ErrorEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private void renderErrorPage(RoutingContext routingContext, Client client) {
    final HttpServerRequest request = routingContext.request();
    final String error = request.getParam(ERROR_PARAM);
    String errorDescription = request.getParam(ERROR_DESCRIPTION_PARAM);
    if (errorDescription != null) {
        try {
            errorDescription = java.net.URLDecoder.decode(request.getParam(ERROR_DESCRIPTION_PARAM), StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            // unable to decode UTF-8 encoded query parameter
        }
    }
    routingContext.put(ERROR_PARAM, error);
    routingContext.put(ERROR_DESCRIPTION_PARAM, errorDescription);
    engine.render(routingContext.data(), getTemplateFileName(client), res -> {
        if (res.succeeded()) {
            routingContext.response().putHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML);
            routingContext.response().end(res.result());
        } else {
            routingContext.fail(res.cause());
        }
    });
}
 
Example 7
Source File: UserBodyRequestParseHandler.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    HttpServerRequest req = context.request();
    if (req.method() != HttpMethod.POST) {
        context.fail(405); // Must be a POST
    } else {
        if (!req.isExpectMultipart()) {
            throw new IllegalStateException("Form body not parsed - do you forget to include a BodyHandler?");
        }
        // check required parameters
        MultiMap params = req.formAttributes();
        Optional<String> missingParameter = requiredParams.stream().filter(param -> {
            String paramValue = params.get(param);
            if (paramValue == null) {
                logger.warn("No {} provided in form - did you forget to include a BodyHandler?", param);
                return true;
            }
            return false;
        }).findFirst();

        if (missingParameter.isPresent()) {
            redirectToPage(context, Collections.singletonMap(ERROR_PARAM, "missing_required_parameters"));
        } else {
            context.next();
        }
    }

}
 
Example 8
Source File: MFAChallengeEndpoint.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    HttpServerRequest req = routingContext.request();
    switch (req.method()) {
        case GET:
            renderMFAPage(routingContext);
            break;
        case POST:
            verifyCode(routingContext);
            break;
        default:
            routingContext.fail(405);
    }
}
 
Example 9
Source File: MFAEnrollEndpoint.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    HttpServerRequest req = routingContext.request();
    switch (req.method()) {
        case GET:
            renderPage(routingContext);
            break;
        case POST:
            saveEnrollment(routingContext);
            break;
        default:
            routingContext.fail(405);
    }
}
 
Example 10
Source File: ResetPasswordEndpoint.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    final HttpServerRequest request = routingContext.request();
    final String error = request.getParam(ERROR_PARAM);
    final String success = request.getParam(SUCCESS_PARAM);
    final String warning = request.getParam(WARNING_PARAM);
    final String token = request.getParam(TOKEN_PARAM);
    // add query params to context
    routingContext.put(ERROR_PARAM, error);
    routingContext.put(SUCCESS_PARAM, success);
    routingContext.put(WARNING_PARAM, warning);
    routingContext.put(TOKEN_PARAM, token);

    // retrieve user who want to reset password
    User user = routingContext.get("user");
    routingContext.put("user", user);

    // retrieve client (if exists)
    Client client = routingContext.get("client");

    // render the reset password page
    engine.render(routingContext.data(), getTemplateFileName(client), res -> {
        if (res.succeeded()) {
            routingContext.response().putHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML);
            routingContext.response().end(res.result());
        } else {
            logger.error("Unable to render reset password page", res.cause());
            routingContext.fail(res.cause());
        }
    });
}
 
Example 11
Source File: RegisterEndpoint.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    final HttpServerRequest request = routingContext.request();
    final String error = request.getParam(ERROR_PARAM);
    final String success = request.getParam(SUCCESS_PARAM);
    final String warning = request.getParam(WARNING_PARAM);
    final String token = request.getParam(TOKEN_PARAM);
    final Client client = routingContext.get("client");
    // add query params to context
    routingContext.put(ERROR_PARAM, error);
    routingContext.put(SUCCESS_PARAM, success);
    routingContext.put(WARNING_PARAM, warning);
    routingContext.put(TOKEN_PARAM, token);

    // set client_id
    Map<String, String> params = new HashMap<>();
    params.put(Parameters.CLIENT_ID, request.getParam(Parameters.CLIENT_ID));
    routingContext.put(PARAM_CONTEXT_KEY, params);

    // render the registration confirmation page
    engine.render(routingContext.data(), getTemplateFileName(client), res -> {
        if (res.succeeded()) {
            routingContext.response().putHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML);
            routingContext.response().end(res.result());
        } else {
            logger.error("Unable to render registration page", res.cause());
            routingContext.fail(res.cause());
        }
    });
}
 
Example 12
Source File: RegisterConfirmationEndpoint.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    final HttpServerRequest request = routingContext.request();
    final String error = request.getParam(ERROR_PARAM);
    final String success = request.getParam(SUCCESS_PARAM);
    final String warning = request.getParam(WARNING_PARAM);
    final String token = request.getParam(TOKEN_PARAM);
    // add query params to context
    routingContext.put(ERROR_PARAM, error);
    routingContext.put(SUCCESS_PARAM, success);
    routingContext.put(WARNING_PARAM, warning);
    routingContext.put(TOKEN_PARAM, token);

    // retrieve user who want to register
    User user = routingContext.get("user");
    routingContext.put("user", user);

    // retrieve client (if exists)
    Client client = routingContext.get("client");

    // check if user has already completed its registration
    if (user != null && user.isPreRegistration() && user.isRegistrationCompleted()) {
        Map<String, String> parameters = new LinkedHashMap<>();
        parameters.put(Parameters.CLIENT_ID, client.getClientId());
        parameters.put(ERROR_PARAM, "invalid_registration_context");
        redirectToPage(routingContext, parameters);
        return;
    }

    // render the registration confirmation page
    engine.render(routingContext.data(), getTemplateFileName(client), res -> {
        if (res.succeeded()) {
            routingContext.response().putHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML);
            routingContext.response().end(res.result());
        } else {
            logger.error("Unable to render registration confirmation page", res.cause());
            routingContext.fail(res.cause());
        }
    });
}
 
Example 13
Source File: OAuth2AuthHandlerImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private void parseAuthorization(RoutingContext context, Handler<AsyncResult<String>> handler) {
    final HttpServerRequest request = context.request();
    final String authorization = request.headers().get(io.vertx.core.http.HttpHeaders.AUTHORIZATION);
    String authToken = null;
    try {
        if (authorization != null) {
            // authorization header has been found check the value
            int idx = authorization.indexOf(' ');

            if (idx <= 0) {
                handler.handle(Future.failedFuture(new InvalidRequestException("The access token must be sent using the Authorization header field")));
                return;
            }

            if (!BEARER.equalsIgnoreCase(authorization.substring(0, idx))) {
                handler.handle(Future.failedFuture(new HttpStatusException(401)));
                return;
            }
            authToken = authorization.substring(idx + 1);
        } else {
            // if no authorization header found, check authorization in body
            authToken = request.getParam(ACCESS_TOKEN);
        }

        if (authToken == null) {
            handler.handle(Future.failedFuture(new HttpStatusException(401)));
            return;
        }

        handler.handle(Future.succeededFuture(authToken));
    }  catch (RuntimeException e) {
        handler.handle(Future.failedFuture(e));
    }
}
 
Example 14
Source File: ClientAuthHandlerImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    final HttpServerRequest request = routingContext.request();

    // fetch client
    resolveClient(request, handler -> {
        if (handler.failed()) {
            routingContext.fail(handler.cause());
            return;
        }
        // authenticate client
        Client client = handler.result();
        authenticateClient(client, request, authHandler -> {
            if (authHandler.failed()) {
                Throwable throwable = authHandler.cause();
                if (throwable instanceof InvalidClientException) {
                    String authenticateHeader = ((InvalidClientException) throwable).getAuthenticateHeader();
                    if (authenticateHeader != null) {
                        routingContext.response().putHeader("WWW-Authenticate", authenticateHeader);
                    }
                }
                routingContext.fail(authHandler.cause());
                return;
            }

            // the client might has been upgraded after authentication process, get the new value
            Client authenticatedClient = authHandler.result();
            // put client in context and continue
            routingContext.put(CLIENT_CONTEXT_KEY, authenticatedClient);
            routingContext.next();
        });

    });

}
 
Example 15
Source File: UserConsentProcessHandler.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    final HttpServerRequest request = routingContext.request();
    final Session session = routingContext.session();
    final Client client = routingContext.get(CLIENT_CONTEXT_KEY);
    final io.gravitee.am.model.User user = ((User) routingContext.user().getDelegate()).getUser();
    final Set<String> requestedConsent = session.get(REQUESTED_CONSENT_CONTEXT_KEY);
    final AuthorizationRequest authorizationRequest = session.get(OAuth2Constants.AUTHORIZATION_REQUEST);

    // get user consent
    MultiMap params = routingContext.request().formAttributes();
    Map<String, String> userConsent = params.entries().stream()
            .filter(entry -> entry.getKey().startsWith(SCOPE_PREFIX))
            .collect(Collectors.toMap(scopeEntry -> scopeEntry.getKey(), scopeEntry -> params.get(USER_OAUTH_APPROVAL)));

    // compute user consent that have been approved / denied
    Set<String> approvedConsent = new HashSet<>();
    List<ScopeApproval> approvals = new ArrayList<>();
    for (String requestedScope : requestedConsent) {
        String approvalParameter = requestedScope;
        String value = userConsent.get(SCOPE_PREFIX + approvalParameter);
        value = value == null ? "" : value.toLowerCase();
        if ("true".equals(value) || value.startsWith("approve")) {
            approvedConsent.add(requestedScope);
            approvals.add(new ScopeApproval(authorizationRequest.transactionId(), user.getId(), client.getClientId(), domain.getId(),
                    requestedScope, ScopeApproval.ApprovalStatus.APPROVED));
        }
        else {
            approvals.add(new ScopeApproval(authorizationRequest.transactionId(), user.getId(), client.getClientId(), domain.getId(),
                    requestedScope, ScopeApproval.ApprovalStatus.DENIED));
        }
    }

    // save consent
    saveConsent(request, user, client, approvals, h -> {
        if (h.failed()) {
            routingContext.fail(h.cause());
            return;
        }

        boolean approved = (approvedConsent.isEmpty() && !requestedConsent.isEmpty()) ? false : true;
        authorizationRequest.setApproved(approved);
        authorizationRequest.setScopes(approvedConsent);
        authorizationRequest.setConsents(h.result());
        session.put(USER_CONSENT_COMPLETED_CONTEXT_KEY, true);
        routingContext.next();
    });
}
 
Example 16
Source File: AuthorizationRequestEndUserConsentHandler.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    final Session session = routingContext.session();
    final HttpServerRequest request = routingContext.request();
    final Client client = routingContext.get(CLIENT_CONTEXT_KEY);
    final io.gravitee.am.model.User user = routingContext.user() != null ? ((User) routingContext.user().getDelegate()).getUser() : null;
    final AuthorizationRequest authorizationRequest = session.get(OAuth2Constants.AUTHORIZATION_REQUEST);
    final Set<String> requestedConsent = authorizationRequest.getScopes();
    // no consent to check, continue
    if (requestedConsent == null || requestedConsent.isEmpty()) {
        routingContext.next();
        return;
    }
    // check if user is already set its consent
    if (session.get(USER_CONSENT_COMPLETED_CONTEXT_KEY) != null && session.get(USER_CONSENT_COMPLETED_CONTEXT_KEY).equals(true)) {
        if (authorizationRequest.isApproved()) {
            routingContext.next();
            return;
        }
        // if prompt=none and the Client does not have pre-configured consent for the requested Claims, throw interaction_required exception
        // https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
        String prompt = request.params().get(Parameters.PROMPT);
        if (prompt != null && Arrays.asList(prompt.split("\\s+")).contains("none")) {
            routingContext.fail(new InteractionRequiredException("Interaction required"));
        } else {
            routingContext.fail(new AccessDeniedException("User denied access"));
        }
        return;
    }
    // application has forced to prompt consent screen to the user
    // go to the user consent page
    if (request.params().contains(Parameters.PROMPT)
            && request.params().get(Parameters.PROMPT).contains("consent")) {
        session.put(REQUESTED_CONSENT_CONTEXT_KEY, requestedConsent);
        redirectToConsentPage(request);
        return;
    }
    // check if application has enabled skip consent option
    if (skipConsent(requestedConsent, client)) {
        authorizationRequest.setApproved(true);
        routingContext.next();
        return;
    }
    // check user consent
    checkUserConsent(client, user, h -> {
        if (h.failed()) {
            routingContext.fail(h.cause());
            return;
        }
        Set<String> approvedConsent = h.result();
        // user approved consent, continue
        if (approvedConsent.containsAll(requestedConsent)) {
            authorizationRequest.setApproved(true);
            routingContext.next();
            return;
        }
        // else go to the user consent page
        Set<String> requiredConsent = requestedConsent.stream().filter(requestedScope -> !approvedConsent.contains(requestedScope)).collect(Collectors.toSet());
        session.put(REQUESTED_CONSENT_CONTEXT_KEY, requiredConsent);
        redirectToConsentPage(request);
    });
}