Example usage for io.vertx.core.http HttpMethod POST

List of usage examples for io.vertx.core.http HttpMethod POST

Introduction

In this page you can find the example usage for io.vertx.core.http HttpMethod POST.

Prototype

HttpMethod POST

To view the source code for io.vertx.core.http HttpMethod POST.

Click Source Link

Usage

From source file:io.github.cdelmas.spike.vertx.Main.java

License:Apache License

public static void main(String[] args) {
    long time = System.currentTimeMillis();
    Json.mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    Vertx vertx = Vertx.vertx();// w ww  . j  a  v  a 2 s  .  c o m

    Router router = Router.router(vertx);

    HelloResource helloResource = new HelloResource();
    router.get("/vertx/hello").produces("application/json").handler(helloResource::hello);
    router.route("/vertx/hello").method(HttpMethod.POST).handler(BodyHandler.create());
    router.post("/vertx/hello").consumes("application/json").handler(helloResource::createMessage);

    HttpServerOptions serverOptions = new HttpServerOptions().setPort(8085);
    HttpServer server = vertx.createHttpServer(serverOptions);
    server.requestHandler(router::accept).listen();
    System.out.println("started in " + (System.currentTimeMillis() - time) + " ms");
}

From source file:io.gravitee.am.gateway.handler.vertx.auth.handler.impl.FormLoginHandlerImpl.java

License:Apache License

@Override
public void handle(RoutingContext context) {
    HttpServerRequest req = context.request();
    if (req.method() != HttpMethod.POST) {
        context.fail(405); // Must be a POST
    } else {//ww w  .ja va2  s . co  m
        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(OAuth2Constants.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();
            JsonObject authInfo = new JsonObject().put("username", username).put("password", password)
                    .put(OAuth2Constants.CLIENT_ID, clientId);
            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();

                        // 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 {
                    try {
                        Map<String, String> parameters = new HashMap<>();
                        parameters.put(OAuth2Constants.CLIENT_ID, clientId);
                        parameters.put("error", "login_failed");
                        String uri = UriBuilderRequest.resolveProxyRequest(
                                new io.vertx.reactivex.core.http.HttpServerRequest(req), req.uri(), parameters,
                                false, false);

                        doRedirect(context.response(), uri);
                    } catch (URISyntaxException e) {
                        context.fail(503);
                    }
                }
            });
        }
    }
}

From source file:io.gravitee.am.gateway.handler.vertx.handler.oauth2.OAuth2Router.java

License:Apache License

public Router route(AuthProvider userAuthProvider) {
    // Create the OAuth 2.0 router
    final Router router = Router.router(vertx);

    // create authentication handlers
    final AuthProvider clientAuthProvider = new AuthProvider(new ClientAuthenticationProvider(clientService));

    final AuthHandler clientAuthHandler = ChainAuthHandler.create()
            .append(ClientCredentialsAuthHandler.create(clientAuthProvider.getDelegate()))
            .append(ClientBasicAuthHandler.create(clientAuthProvider.getDelegate()));

    final AuthHandler userAuthHandler = RedirectAuthHandler.create(userAuthProvider.getDelegate(),
            '/' + domain.getPath() + "/login");

    // create other handlers
    final AuthorizationRequestParseHandler authorizationRequestParseHandler = AuthorizationRequestParseHandler
            .create(domain);//  ww  w . j a  v a2  s.  c  o m

    // Bind OAuth2 endpoints
    Handler<RoutingContext> authorizeEndpoint = new AuthorizationEndpointHandler(authorizationCodeService,
            tokenGranter, clientService, approvalService, domain);
    Handler<RoutingContext> authorizeApprovalEndpoint = new AuthorizationApprovalEndpointHandler(
            authorizationCodeService, tokenGranter, approvalService, clientService);
    Handler<RoutingContext> tokenEndpoint = new TokenEndpointHandler(tokenGranter);
    Handler<RoutingContext> userApprovalEndpoint = new UserApprovalEndpointHandler(clientService, scopeService,
            thymeleafTemplateEngine);

    // Check_token is provided only for backward compatibility and must be remove in the future
    Handler<RoutingContext> checkTokenEndpoint = new CheckTokenEndpointHandler();
    ((CheckTokenEndpointHandler) checkTokenEndpoint).setTokenService(tokenService);

    Handler<RoutingContext> introspectionEndpoint = new IntrospectionEndpointHandler();
    ((IntrospectionEndpointHandler) introspectionEndpoint).setIntrospectionService(introspectionService);

    // Revocation token endpoint
    Handler<RoutingContext> revocationTokenEndpoint = new RevocationTokenEndpointHandler(
            revocationTokenService);

    // declare oauth2 routes
    router.route(HttpMethod.GET, "/authorize").handler(authorizationRequestParseHandler)
            .handler(userAuthHandler).handler(authorizeEndpoint);
    router.route(HttpMethod.POST, "/authorize").handler(userAuthHandler).handler(authorizeApprovalEndpoint);
    router.route(HttpMethod.POST, "/token").handler(clientAuthHandler).handler(tokenEndpoint);
    router.route(HttpMethod.POST, "/check_token").consumes(MediaType.APPLICATION_FORM_URLENCODED)
            .handler(clientAuthHandler).handler(checkTokenEndpoint);
    router.route(HttpMethod.POST, "/introspect").consumes(MediaType.APPLICATION_FORM_URLENCODED)
            .handler(clientAuthHandler).handler(introspectionEndpoint);
    router.route(HttpMethod.POST, "/revoke").consumes(MediaType.APPLICATION_FORM_URLENCODED)
            .handler(clientAuthHandler).handler(revocationTokenEndpoint);
    router.route(HttpMethod.GET, "/confirm_access").handler(userApprovalEndpoint);
    router.route(HttpMethod.GET, "/error").handler(new ErrorHandlerEndpoint(thymeleafTemplateEngine));

    return router;
}

From source file:io.gravitee.am.gateway.handler.vertx.handler.oidc.handler.UserInfoRequestParseHandler.java

License:Apache License

@Override
public void handle(RoutingContext context) {
    final HttpServerRequest request = context.request();
    String accessToken = null;//from  w  ww.  ja v a2s.c  o  m

    // Try to get the access token from the body request
    if (request.method().equals(HttpMethod.POST)) {
        accessToken = context.request().getParam(ACCESS_TOKEN_PARAM);
    }

    // no access token try to get one from the HTTP Authorization header
    if (accessToken == null || accessToken.isEmpty()) {
        final String authorization = request.headers().get(HttpHeaders.AUTHORIZATION);

        if (authorization == null) {
            throw new InvalidRequestException("An access token is required");
        }

        int idx = authorization.indexOf(' ');
        if (idx <= 0 || !BEARER.equalsIgnoreCase(authorization.substring(0, idx))) {
            throw new InvalidRequestException(
                    "The access token must be sent using the Authorization header field");
        }

        accessToken = authorization.substring(idx + 1);
    }

    tokenService.getAccessToken(accessToken).map(accessToken1 -> {
        if (accessToken1.getExpiresIn() == 0) {
            throw new InvalidTokenException("The access token expired");
        }
        // The Access Token must be obtained from an OpenID Connect Authentication Request (i.e should have at least openid scope)
        // https://openid.net/specs/openid-connect-core-1_0.html#UserInfoRequest
        if (accessToken1.getScope() == null
                || !Arrays.asList(accessToken1.getScope().split("\\s+")).contains(OPENID_SCOPE)) {
            throw new InvalidTokenException(
                    "Invalid access token scopes. The access token should have at least 'openid' scope");
        }
        return accessToken1;
    }).subscribe(accessToken1 -> {
        context.put(AccessToken.ACCESS_TOKEN, accessToken1);
        context.next();
    }, error -> context.fail(error), () -> context.fail(new InvalidTokenException()));
}

From source file:io.gravitee.am.gateway.handler.vertx.handler.oidc.OIDCRouter.java

License:Apache License

public Router route() {
    // Create the OpenID Connect router
    final Router router = Router.router(vertx);

    // OpenID Provider Configuration Information Endpoint
    Handler<RoutingContext> openIDProviderConfigurationEndpoint = new ProviderConfigurationEndpoint();
    ((ProviderConfigurationEndpoint) openIDProviderConfigurationEndpoint).setDiscoveryService(discoveryService);
    router.route(HttpMethod.GET, "/.well-known/openid-configuration")
            .handler(openIDProviderConfigurationEndpoint);

    // UserInfo Endpoint
    Handler<RoutingContext> userInfoEndpoint = new UserInfoEndpoint(userService);
    Handler<RoutingContext> userInfoRequestParseHandler = new UserInfoRequestParseHandler(tokenService);
    router.route("/userinfo").handler(CorsHandler.newInstance(corsHandler()));
    router.route(HttpMethod.GET, "/userinfo").handler(userInfoRequestParseHandler).handler(userInfoEndpoint);
    router.route(HttpMethod.POST, "/userinfo").consumes(MediaType.APPLICATION_FORM_URLENCODED)
            .handler(userInfoRequestParseHandler).handler(userInfoEndpoint);

    // OpenID Provider JWK Set
    Handler<RoutingContext> openIDProviderJWKSetEndpoint = new ProviderJWKSetEndpoint();
    ((ProviderJWKSetEndpoint) openIDProviderJWKSetEndpoint).setJwkSetService(jwkSetService);
    router.route(HttpMethod.GET, "/.well-known/jwks.json").handler(openIDProviderJWKSetEndpoint);

    return router;
}

From source file:io.gravitee.gateway.http.vertx.VertxHttpClient.java

License:Apache License

private HttpMethod convert(io.gravitee.common.http.HttpMethod httpMethod) {
    switch (httpMethod) {
    case CONNECT:
        return HttpMethod.CONNECT;
    case DELETE:/* www. j av a 2  s  .  c  om*/
        return HttpMethod.DELETE;
    case GET:
        return HttpMethod.GET;
    case HEAD:
        return HttpMethod.HEAD;
    case OPTIONS:
        return HttpMethod.OPTIONS;
    case PATCH:
        return HttpMethod.PATCH;
    case POST:
        return HttpMethod.POST;
    case PUT:
        return HttpMethod.PUT;
    case TRACE:
        return HttpMethod.TRACE;
    }

    return null;
}

From source file:io.gravitee.resource.oauth2.generic.OAuth2GenericResource.java

License:Apache License

@Override
public void introspect(String accessToken, Handler<OAuth2Response> responseHandler) {
    HttpClient httpClient = httpClients.computeIfAbsent(Vertx.currentContext(),
            context -> vertx.createHttpClient(httpClientOptions));

    OAuth2ResourceConfiguration configuration = configuration();
    StringBuilder introspectionUriBuilder = new StringBuilder(introspectionEndpointURI);

    if (configuration.isTokenIsSuppliedByQueryParam()) {
        introspectionUriBuilder.append('?').append(configuration.getTokenQueryParamName()).append('=')
                .append(accessToken);/*  ww w. ja v a 2 s . c o m*/
    }

    String introspectionEndpointURI = introspectionUriBuilder.toString();
    logger.debug("Introspect access token by requesting {} [{}]", introspectionEndpointURI,
            configuration.getIntrospectionEndpointMethod());

    HttpMethod httpMethod = HttpMethod.valueOf(configuration.getIntrospectionEndpointMethod().toUpperCase());

    HttpClientRequest request = httpClient.requestAbs(httpMethod, introspectionEndpointURI);
    request.setTimeout(30000L);

    if (configuration().isUseClientAuthorizationHeader()) {
        String authorizationHeader = configuration.getClientAuthorizationHeaderName();
        String authorizationValue = configuration.getClientAuthorizationHeaderScheme().trim()
                + AUTHORIZATION_HEADER_SCHEME_SEPARATOR
                + Base64.getEncoder().encodeToString(
                        (configuration.getClientId() + AUTHORIZATION_HEADER_VALUE_BASE64_SEPARATOR
                                + configuration.getClientSecret()).getBytes());
        request.headers().add(authorizationHeader, authorizationValue);
        logger.debug("Set client authorization using HTTP header {} with value {}", authorizationHeader,
                authorizationValue);
    }

    // Set `Accept` header to ask for application/json content
    request.headers().add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);

    if (configuration.isTokenIsSuppliedByHttpHeader()) {
        request.headers().add(configuration.getTokenHeaderName(), accessToken);
    }

    request.handler(response -> response.bodyHandler(buffer -> {
        logger.debug("Introspection endpoint returns a response with a {} status code", response.statusCode());
        if (response.statusCode() == HttpStatusCode.OK_200) {
            // According to RFC 7662 : Note that a properly formed and authorized query for an inactive or
            // otherwise invalid token (or a token the protected resource is not
            // allowed to know about) is not considered an error response by this
            // specification.  In these cases, the authorization server MUST instead
            // respond with an introspection response with the "active" field set to
            // "false" as described in Section 2.2.
            String content = buffer.toString();

            try {
                JsonNode introspectNode = MAPPER.readTree(content);
                JsonNode activeNode = introspectNode.get("active");
                if (activeNode != null) {
                    boolean isActive = activeNode.asBoolean();
                    responseHandler.handle(new OAuth2Response(isActive, content));
                } else {
                    responseHandler.handle(new OAuth2Response(true, content));
                }
            } catch (IOException e) {
                logger.error("Unable to validate introspection endpoint payload: {}", content);
                responseHandler.handle(new OAuth2Response(false, content));
            }
        } else {
            responseHandler.handle(new OAuth2Response(false, buffer.toString()));
        }
    }));

    request.exceptionHandler(event -> {
        logger.error("An error occurs while checking OAuth2 token", event);
        responseHandler.handle(new OAuth2Response(false, event.getMessage()));
    });

    if (httpMethod == HttpMethod.POST && configuration.isTokenIsSuppliedByFormUrlEncoded()) {
        request.headers().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
        request.end(configuration.getTokenFormUrlEncodedName() + '=' + accessToken);
    } else {
        request.end();
    }
}

From source file:io.knotx.adapter.action.http.impl.HttpActionAdapterProxyImpl.java

License:Apache License

@Override
protected Observable<AdapterResponse> processRequest(AdapterRequest request) {
    return httpClientFacade.process(request, HttpMethod.POST).map(this::prepareResponse);
}

From source file:io.knotx.mocks.MockServiceVerticle.java

License:Apache License

@Override
public void start(Future<Void> fut) throws IOException, URISyntaxException {
    LOGGER.info("Starting <{}>", this.getClass().getSimpleName());
    httpServer = vertx.createHttpServer();

    Router router = Router.router(vertx);
    router.route().handler(BodyHandler.create());
    router.route().method(HttpMethod.POST).handler(createPostHandler());
    router.route().method(HttpMethod.GET).handler(createGetHandler());

    router.route().failureHandler(ErrorHandler.create(true));
    httpServer.requestHandler(router::accept).listen(config().getInteger("httpPort"), result -> {
        if (result.succeeded()) {
            LOGGER.info("Mock Service server started. Listening on port {}", config().getInteger("httpPort"));
            fut.complete();//from  w  w w.  j a  v  a  2s.  co m
        } else {
            LOGGER.error("Unable to start Mock Service server.", result.cause());
            fut.fail(result.cause());
        }
    });
}

From source file:io.knotx.server.KnotxServerVerticle.java

License:Apache License

@Override
public void start(Future<Void> fut) throws IOException, URISyntaxException {
    LOGGER.info("Starting <{}>", this.getClass().getSimpleName());
    Router router = Router.router(vertx);

    router.route().handler(SupportedMethodsAndPathsHandler.create(configuration));
    configuration.getEngineRouting().entrySet().forEach(entry -> {
        if (entry.getKey() == HttpMethod.POST) {
            router.route().method(entry.getKey()).handler(BodyHandler.create());
        }// w w  w.j a  va  2  s .c  om
        entry.getValue().forEach(criteria -> {
            router.route().method(entry.getKey()).pathRegex(criteria.path())
                    .handler(KnotxRepositoryHandler.create(vertx, configuration));

            router.route().method(entry.getKey()).pathRegex(criteria.path())
                    .handler(KnotxSplitterHandler.create(vertx, configuration));

            router.route().method(entry.getKey()).pathRegex(criteria.path())
                    .handler(KnotxEngineHandler.create(vertx, criteria.address(), criteria.onTransition()));

            router.route().method(entry.getKey()).pathRegex(criteria.path())
                    .handler(KnotxAssemblerHandler.create(vertx, configuration));
        });
    });
    router.route().failureHandler(ErrorHandler.create(configuration.displayExceptionDetails()));

    vertx.createHttpServer().requestHandler(router::accept).rxListen(configuration.httpPort()).subscribe(ok -> {
        LOGGER.info("Knot.x HTTP Server started. Listening on port {}", configuration.httpPort());
        fut.complete();
    }, error -> {
        LOGGER.error("Unable to start Knot.x HTTP Server.", error.getCause());
        fut.fail(error.getCause());
    });

}