Java Code Examples for io.vertx.core.http.HttpServerRequest#method()

The following examples show how to use io.vertx.core.http.HttpServerRequest#method() . 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: SmallRyeGraphQLExecutionHandler.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private void doHandle(final RoutingContext ctx) {
    if (currentIdentityAssociation != null) {
        currentIdentityAssociation.setIdentity(QuarkusHttpUser.getSecurityIdentity(ctx, null));
    }

    HttpServerRequest request = ctx.request();
    HttpServerResponse response = ctx.response();

    response.headers().set(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");

    switch (request.method()) {
        case OPTIONS:
            handleOptions(response);
            break;
        case POST:
            handlePost(response, ctx);
            break;
        case GET:
            handleGet(response, ctx);
            break;
        default:
            response.setStatusCode(405).end();
            break;
    }
}
 
Example 2
Source File: NexusHttpProxy.java    From nexus-proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Proxies the specified HTTP request, enriching its headers with authentication information.
 *
 * @param userId  the ID of the user making the request.
 * @param origReq the original request (i.e., {@link RoutingContext#request()}.
 * @param origRes the original response (i.e., {@link RoutingContext#request()}.
 */
public void proxyUserRequest(final String userId,
                             final HttpServerRequest origReq,
                             final HttpServerResponse origRes) {
    final Handler<HttpClientResponse> proxiedResHandler = proxiedRes -> {
        origRes.setChunked(true);
        origRes.setStatusCode(proxiedRes.statusCode());
        origRes.headers().setAll(proxiedRes.headers());
        proxiedRes.handler(origRes::write);
        proxiedRes.endHandler(v -> origRes.end());
    };

    final HttpClientRequest proxiedReq;
    proxiedReq = httpClient.request(origReq.method(), port, host, origReq.uri(), proxiedResHandler);
    if(origReq.method() == HttpMethod.OTHER) {
        proxiedReq.setRawMethod(origReq.rawMethod());
    }
    proxiedReq.setChunked(true);
    proxiedReq.headers().add(X_FORWARDED_PROTO, getHeader(origReq, X_FORWARDED_PROTO, origReq.scheme()));
    proxiedReq.headers().add(X_FORWARDED_FOR, getHeader(origReq, X_FORWARDED_FOR, origReq.remoteAddress().host()));
    proxiedReq.headers().addAll(origReq.headers());
    injectRutHeader(proxiedReq, userId);
    origReq.handler(proxiedReq::write);
    origReq.endHandler(v -> proxiedReq.end());
}
 
Example 3
Source File: SocialAuthHandlerImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private boolean handlePreflight(RoutingContext ctx) {
    final HttpServerRequest request = ctx.request();
    // See: https://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0
    // Preflight requests should not be subject to security due to the reason UAs will remove the Authorization header
    if (request.method() == HttpMethod.OPTIONS) {
        // check if there is a access control request header
        final String accessControlRequestHeader = ctx.request().getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
        if (accessControlRequestHeader != null) {
            // lookup for the Authorization header
            for (String ctrlReq : accessControlRequestHeader.split(",")) {
                if (ctrlReq.equalsIgnoreCase("Authorization")) {
                    // this request has auth in access control, so we can allow preflighs without authentication
                    ctx.next();
                    return true;
                }
            }
        }
    }

    return false;
}
 
Example 4
Source File: AuthHandlerImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private boolean handlePreflight(RoutingContext ctx) {
  final HttpServerRequest request = ctx.request();
  // See: https://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0
  // Preflight requests should not be subject to security due to the reason UAs will remove the Authorization header
  if (request.method() == HttpMethod.OPTIONS) {
    // check if there is a access control request header
    final String accessControlRequestHeader = ctx.request().getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
    if (accessControlRequestHeader != null) {
      // lookup for the Authorization header
      for (String ctrlReq : accessControlRequestHeader.split(",")) {
        if (ctrlReq.equalsIgnoreCase("Authorization")) {
          // this request has auth in access control, so we can allow preflighs without authentication
          ctx.next();
          return true;
        }
      }
    }
  }

  return false;
}
 
Example 5
Source File: AuthenticationHandlerImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private boolean handlePreflight(RoutingContext ctx) {
  final HttpServerRequest request = ctx.request();
  // See: https://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0
  // Preflight requests should not be subject to security due to the reason UAs will remove the Authorization header
  if (request.method() == HttpMethod.OPTIONS) {
    // check if there is a access control request header
    final String accessControlRequestHeader = ctx.request().getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
    if (accessControlRequestHeader != null) {
      // lookup for the Authorization header
      for (String ctrlReq : accessControlRequestHeader.split(",")) {
        if (ctrlReq.equalsIgnoreCase("Authorization")) {
          // this request has auth in access control, so we can allow preflighs without authentication
          ctx.next();
          return true;
        }
      }
    }
  }

  return false;
}
 
Example 6
Source File: AbstractHttpMessageHandler.java    From festival with Apache License 2.0 5 votes vote down vote up
@Override
public Object[] handle(RoutingContext routingContext, Parameter[] parameters) throws Exception {
    HttpServerRequest httpServerRequest = routingContext.request();
    HttpMethod httpMethod = httpServerRequest.method();
    if (httpMethod == HttpMethod.GET || httpMethod == HttpMethod.POST
            || httpMethod == HttpMethod.PUT || httpMethod == HttpMethod.DELETE) {
        return doHandle(routingContext, parameters);
    }
    return new Object[0];
}
 
Example 7
Source File: HttpMethodAccessItem.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public void appendServerFormattedItem(ServerAccessLogEvent accessLogEvent, StringBuilder builder) {
  HttpServerRequest request = accessLogEvent.getRoutingContext().request();
  if (null == request || null == request.method()) {
    builder.append(EMPTY_RESULT);
    return;
  }
  builder.append(request.method().toString());
}
 
Example 8
Source File: VertxWebSocketReactorHandler.java    From gravitee-gateway with Apache License 2.0 5 votes vote down vote up
private boolean isWebSocket(HttpServerRequest httpServerRequest) {
    String connectionHeader = httpServerRequest.getHeader(HttpHeaders.CONNECTION);
    String upgradeHeader = httpServerRequest.getHeader(HttpHeaders.UPGRADE);

    return httpServerRequest.method() == HttpMethod.GET &&
            HttpHeaderValues.UPGRADE.contentEqualsIgnoreCase(connectionHeader) &&
            HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(upgradeHeader);
}
 
Example 9
Source File: CorsHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext context) {
  HttpServerRequest request = context.request();
  HttpServerResponse response = context.response();
  String origin = context.request().headers().get(ORIGIN);
  if (origin == null) {
    // Not a CORS request - we don't set any headers and just call the next handler
    context.next();
  } else if (isValidOrigin(origin)) {
    String accessControlRequestMethod = request.headers().get(ACCESS_CONTROL_REQUEST_METHOD);
    if (request.method() == HttpMethod.OPTIONS && accessControlRequestMethod != null) {
      // Pre-flight request
      addCredentialsAndOriginHeader(response, origin);
      if (allowedMethodsString != null) {
        response.putHeader(ACCESS_CONTROL_ALLOW_METHODS, allowedMethodsString);
      }
      if (allowedHeadersString != null) {
        response.putHeader(ACCESS_CONTROL_ALLOW_HEADERS, allowedHeadersString);
      }
      if (maxAgeSeconds != null) {
        response.putHeader(ACCESS_CONTROL_MAX_AGE, maxAgeSeconds);
      }
      // according to MDC although the is no body the response should be OK
      response.setStatusCode(200).end();
    } else {
      addCredentialsAndOriginHeader(response, origin);
      if (exposedHeadersString != null) {
        response.putHeader(ACCESS_CONTROL_EXPOSE_HEADERS, exposedHeadersString);
      }
      context.put(CORS_HANDLED_FLAG, true);
      context.next();
    }
  } else {
    context
      .response()
      .setStatusMessage("CORS Rejected - Invalid origin");
    context
      .fail(403);
  }
}
 
Example 10
Source File: MethodOverrideHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext context) {
  HttpServerRequest request = context.request();

  HttpMethod from = request.method();
  HttpMethod to = methodFromHeader(request);

  if (to != null && from != to && canOverride(from, to)) {
    context.reroute(to, request.path());
  } else {
    context.next();
  }
}
 
Example 11
Source File: VertxRequestHandler.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private void dispatch(RoutingContext routingContext, InputStream is, VertxOutput output) {
    ManagedContext requestContext = beanContainer.requestContext();
    requestContext.activate();
    routingContext.remove(QuarkusHttpUser.AUTH_FAILURE_HANDLER);
    QuarkusHttpUser user = (QuarkusHttpUser) routingContext.user();
    if (association != null) {
        association.setIdentity(QuarkusHttpUser.getSecurityIdentity(routingContext, null));
    }
    currentVertxRequest.setCurrent(routingContext);
    try {
        Context ctx = vertx.getOrCreateContext();
        HttpServerRequest request = routingContext.request();
        ResteasyUriInfo uriInfo = VertxUtil.extractUriInfo(request, rootPath);
        ResteasyHttpHeaders headers = VertxUtil.extractHttpHeaders(request);
        HttpServerResponse response = request.response();
        VertxHttpResponse vertxResponse = new VertxHttpResponse(request, dispatcher.getProviderFactory(),
                request.method(), allocator, output);

        // using a supplier to make the remote Address resolution lazy: often it's not needed and it's not very cheap to create.
        LazyHostSupplier hostSupplier = new LazyHostSupplier(request);

        VertxHttpRequest vertxRequest = new VertxHttpRequest(ctx, routingContext, headers, uriInfo, request.rawMethod(),
                hostSupplier,
                dispatcher.getDispatcher(), vertxResponse, requestContext);
        vertxRequest.setInputStream(is);
        try {
            ResteasyContext.pushContext(SecurityContext.class, new QuarkusResteasySecurityContext(request, routingContext));
            ResteasyContext.pushContext(RoutingContext.class, routingContext);
            dispatcher.service(ctx, request, response, vertxRequest, vertxResponse, true);
        } catch (Failure e1) {
            vertxResponse.setStatus(e1.getErrorCode());
            if (e1.isLoggable()) {
                log.error(e1);
            }
        } catch (Throwable ex) {
            routingContext.fail(ex);
        }

        boolean suspended = vertxRequest.getAsyncContext().isSuspended();
        boolean requestContextActive = requestContext.isActive();
        if (!suspended) {
            try {
                if (requestContextActive) {
                    requestContext.terminate();
                }
            } finally {
                try {
                    vertxResponse.finish();
                } catch (IOException e) {
                    log.debug("IOException writing JAX-RS response", e);
                }
            }
        } else {
            //we need the request context to stick around
            requestContext.deactivate();
        }
    } catch (Throwable t) {
        try {
            routingContext.fail(t);
        } finally {
            if (requestContext.isActive()) {
                requestContext.terminate();
            }
        }
    }
}
 
Example 12
Source File: FormLoginHandlerImpl.java    From graviteeio-access-management with Apache License 2.0 4 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?");
        }
        MultiMap params = req.formAttributes();
        String username = params.get(usernameParam);
        String password = params.get(passwordParam);
        String clientId = params.get(Parameters.CLIENT_ID);
        if (username == null || password == null) {
            log.warn("No username or password provided in form - did you forget to include a BodyHandler?");
            context.fail(400);
        } else if (clientId == null) {
            log.warn("No client id in form - did you forget to include client_id query parameter ?");
            context.fail(400);
        } else {
            Session session = context.session();

            // build authentication object with ip address and user agent
            JsonObject authInfo = new JsonObject()
                    .put("username", username)
                    .put("password", password)
                    .put(Claims.ip_address, remoteAddress(req))
                    .put(Claims.user_agent, userAgent(req))
                    .put(Parameters.CLIENT_ID, clientId);

            authProvider.authenticate(context, authInfo, res -> {
                if (res.succeeded()) {
                    User user = res.result();
                    context.setUser(user);
                    if (session != null) {
                        // the user has upgraded from unauthenticated to authenticated
                        // session should be upgraded as recommended by owasp
                        session.regenerateId();

                        // Note : keep returnURLParam in session in case the user go to previous page
                        // String returnURL = session.remove(returnURLParam);
                        String returnURL = session.get(returnURLParam);
                        if (returnURL != null) {
                            // Now redirect back to the original url
                            doRedirect(req.response(), returnURL);
                            return;
                        }
                    }
                    // Either no session or no return url
                    if (directLoggedInOKURL != null) {
                        // Redirect to the default logged in OK page - this would occur
                        // if the user logged in directly at this URL without being redirected here first from another
                        // url
                        doRedirect(req.response(), directLoggedInOKURL);
                    } else {
                        // Just show a basic page
                        req.response().end(DEFAULT_DIRECT_LOGGED_IN_OK_PAGE);
                    }
                } else {
                    handleException(context);
                }
            });
        }
    }
}
 
Example 13
Source File: HttpServerMetricsImpl.java    From vertx-dropwizard-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public HttpRequestMetric requestBegin(Long socketMetric, HttpServerRequest request) {
  return new HttpRequestMetric(request.method(), request.uri());
}
 
Example 14
Source File: FormLoginHandlerImpl.java    From vertx-web with Apache License 2.0 4 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("HttpServerRequest should have setExpectMultipart set to true, but it is currently set to false.");
    }
    MultiMap params = req.formAttributes();
    String username = params.get(usernameParam);
    String password = params.get(passwordParam);
    if (username == null || password == null) {
      log.warn("No username or password provided in form - did you forget to include a BodyHandler?");
      context.fail(400);
    } else {
      Session session = context.session();
      UsernamePasswordCredentials authInfo = new UsernamePasswordCredentials(username, password);

      authProvider.authenticate(authInfo, res -> {
        if (res.succeeded()) {
          User user = res.result();
          context.setUser(user);
          if (session != null) {
            // the user has upgraded from unauthenticated to authenticated
            // session should be upgraded as recommended by owasp
            session.regenerateId();

            String returnURL = session.remove(returnURLParam);
            if (returnURL != null) {
              // Now redirect back to the original url
              doRedirect(req.response(), returnURL);
              return;
            }
          }
          // Either no session or no return url
          if (directLoggedInOKURL != null) {
            // Redirect to the default logged in OK page - this would occur
            // if the user logged in directly at this URL without being redirected here first from another
            // url
            doRedirect(req.response(), directLoggedInOKURL);
          } else {
            // Just show a basic page
            req.response().end(DEFAULT_DIRECT_LOGGED_IN_OK_PAGE);
          }
        } else {
          context.fail(401);  // Failed login
        }
      });
    }
  }
}