io.vertx.ext.web.handler.CorsHandler Java Examples
The following examples show how to use
io.vertx.ext.web.handler.CorsHandler.
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: SockJSCORSTest.java From vertx-web with Apache License 2.0 | 6 votes |
@Test public void testNoConflictsSockJSAndCORSHandler() { router .route() .handler(CorsHandler.create("*").allowCredentials(false)) .handler(BodyHandler.create()); SockJSProtocolTest.installTestApplications(router, vertx); client.get("/echo/info?t=21321", HttpHeaders.set(HttpHeaders.ORIGIN, "example.com"), onSuccess(resp -> { assertEquals(200, resp.statusCode()); assertEquals("*", resp.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); assertFalse(resp.headers().contains(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); //If the SockJS handles the CORS stuff, it would reply with allow credentials true and allow origin example.com complete(); })); await(); }
Example #2
Source File: RestAPIVerticle.java From vertx-blueprint-microservice with Apache License 2.0 | 6 votes |
/** * Enable CORS support. * * @param router router instance */ protected void enableCorsSupport(Router router) { Set<String> allowHeaders = new HashSet<>(); allowHeaders.add("x-requested-with"); allowHeaders.add("Access-Control-Allow-Origin"); allowHeaders.add("origin"); allowHeaders.add("Content-Type"); allowHeaders.add("accept"); Set<HttpMethod> allowMethods = new HashSet<>(); allowMethods.add(HttpMethod.GET); allowMethods.add(HttpMethod.PUT); allowMethods.add(HttpMethod.OPTIONS); allowMethods.add(HttpMethod.POST); allowMethods.add(HttpMethod.DELETE); allowMethods.add(HttpMethod.PATCH); router.route().handler(CorsHandler.create("*") .allowedHeaders(allowHeaders) .allowedMethods(allowMethods)); }
Example #3
Source File: RestBuilder.java From rest.vertx with Apache License 2.0 | 6 votes |
/** * Enables CORS * * @param allowedOriginPattern allowed origin * @param allowCredentials allow credentials (true/false) * @param maxAge in seconds * @param allowedHeaders set of allowed headers * @param methods list of methods ... if empty all methods are allowed @return self * @return self */ public RestBuilder enableCors(String allowedOriginPattern, boolean allowCredentials, int maxAge, Set<String> allowedHeaders, HttpMethod... methods) { corsHandler = CorsHandler.create(allowedOriginPattern) .allowCredentials(allowCredentials) .maxAgeSeconds(maxAge); if (methods == null || methods.length == 0) { // if not given than all methods = HttpMethod.values(); } for (HttpMethod method : methods) { corsHandler.allowedMethod(method); } if (allowedHeaders.size() > 0) { corsHandler.allowedHeaders(allowedHeaders); } return this; }
Example #4
Source File: RestRouter.java From rest.vertx with Apache License 2.0 | 6 votes |
/** * @param router to add handler to * @param allowedOriginPattern origin pattern * @param allowCredentials allowed credentials * @param maxAge in seconds * @param allowedHeaders set of headers or null for none * @param methods list of methods or empty for all */ public static void enableCors(Router router, String allowedOriginPattern, boolean allowCredentials, int maxAge, Set<String> allowedHeaders, HttpMethod... methods) { CorsHandler handler = CorsHandler.create(allowedOriginPattern) .allowCredentials(allowCredentials) .maxAgeSeconds(maxAge); if (methods == null || methods.length == 0) { // if not given than all methods = HttpMethod.values(); } for (HttpMethod method : methods) { handler.allowedMethod(method); } handler.allowedHeaders(allowedHeaders); router.route().order(ORDER_CORS_HANDLER).handler(handler); }
Example #5
Source File: VertxBasedHttpProtocolAdapter.java From hono with Eclipse Public License 2.0 | 5 votes |
private void addEventApiRoutes(final Router router, final Handler<RoutingContext> authHandler) { // support CORS headers for PUTing events router.routeWithRegex("\\/event\\/[^\\/]+\\/.*").handler(CorsHandler.create(getConfig().getCorsAllowedOrigin()) .allowedMethod(HttpMethod.PUT) .allowedHeader(Constants.HEADER_TIME_TILL_DISCONNECT) .allowedHeader(HttpHeaders.AUTHORIZATION.toString()) .allowedHeader(HttpHeaders.CONTENT_TYPE.toString()) .exposedHeader(Constants.HEADER_COMMAND) .exposedHeader(Constants.HEADER_COMMAND_REQUEST_ID)); if (getConfig().isAuthenticationRequired()) { // support CORS headers for POSTing events router.route(ROUTE_EVENT_ENDPOINT).handler(CorsHandler.create(getConfig().getCorsAllowedOrigin()) .allowedMethod(HttpMethod.POST) .allowedHeader(Constants.HEADER_TIME_TILL_DISCONNECT) .allowedHeader(HttpHeaders.AUTHORIZATION.toString()) .allowedHeader(HttpHeaders.CONTENT_TYPE.toString()) .exposedHeader(Constants.HEADER_COMMAND) .exposedHeader(Constants.HEADER_COMMAND_REQUEST_ID)); // require auth for POSTing events router.route(HttpMethod.POST, ROUTE_EVENT_ENDPOINT).handler(authHandler); // route for posting events using tenant and device ID determined as part of // device authentication router.route(HttpMethod.POST, ROUTE_EVENT_ENDPOINT).handler(this::handlePostEvent); // require auth for PUTing events router.route(HttpMethod.PUT, "/event/*").handler(authHandler); // route for asserting that authenticated device's tenant matches tenant from path variables router.route(HttpMethod.PUT, String.format("/event/:%s/:%s", PARAM_TENANT, PARAM_DEVICE_ID)) .handler(this::assertTenant); } // route for sending event messages router.route(HttpMethod.PUT, String.format("/event/:%s/:%s", PARAM_TENANT, PARAM_DEVICE_ID)) .handler(ctx -> uploadEventMessage(ctx, getTenantParam(ctx), getDeviceIdParam(ctx))); }
Example #6
Source File: AbstractHttpEndpoint.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * Creates default CORS handler that allows 'POST', 'GET', 'PUT' and 'DELETE' methods for the specified origin. * * @param allowedOrigin The allowed origin pattern. * @return The handler. */ protected final CorsHandler createDefaultCorsHandler(final String allowedOrigin) { return createCorsHandler(allowedOrigin, EnumSet.of( HttpMethod.POST, HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE) ); }
Example #7
Source File: AbstractHttpEndpoint.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * Creates CORS Handler that allows HTTP methods for the specified origin. * * @param allowedOrigin The allowed origin pattern. * @param methods Set of allowed HTTP methods * @return The handler. */ protected final CorsHandler createCorsHandler(final String allowedOrigin, final Set<HttpMethod> methods) { return CorsHandler.create(allowedOrigin) .allowedMethods(methods) .allowedHeader(HttpHeaders.CONTENT_TYPE.toString()) .allowedHeader(HttpHeaders.AUTHORIZATION.toString()) .allowedHeader(HttpHeaders.IF_MATCH.toString()) .exposedHeader(HttpHeaders.ETAG.toString()); }
Example #8
Source File: RestrictedCorsRouterConfig.java From vxms with Apache License 2.0 | 5 votes |
public void corsHandler(Router router) { router .route() .handler( CorsHandler.create("127.0.0.1") .allowedMethod(io.vertx.core.http.HttpMethod.GET) .allowedMethod(io.vertx.core.http.HttpMethod.POST) .allowedMethod(io.vertx.core.http.HttpMethod.OPTIONS) .allowedMethod(io.vertx.core.http.HttpMethod.PUT) .allowedMethod(io.vertx.core.http.HttpMethod.DELETE) .allowedHeader("Content-Type") .allowedHeader("X-Requested-With")); }
Example #9
Source File: RestrictedCorsRouterConfig2.java From vxms with Apache License 2.0 | 5 votes |
public void corsHandler(Router router) { router .route() .handler( CorsHandler.create("http://example.com") .allowedMethod(io.vertx.core.http.HttpMethod.GET) .allowedMethod(io.vertx.core.http.HttpMethod.POST) .allowedMethod(io.vertx.core.http.HttpMethod.OPTIONS) .allowedMethod(io.vertx.core.http.HttpMethod.PUT) .allowedMethod(io.vertx.core.http.HttpMethod.DELETE) .allowedHeader("Content-Type") .allowedHeader("X-Requested-With")); }
Example #10
Source File: RestrictedBodyHandlingRouterConfig.java From vxms with Apache License 2.0 | 5 votes |
public void corsHandler(Router router) { router .route() .handler( CorsHandler.create("*") .allowedMethod(io.vertx.core.http.HttpMethod.GET) .allowedMethod(io.vertx.core.http.HttpMethod.POST) .allowedMethod(io.vertx.core.http.HttpMethod.OPTIONS) .allowedMethod(io.vertx.core.http.HttpMethod.PUT) .allowedMethod(io.vertx.core.http.HttpMethod.DELETE) .allowedHeader("Content-Type") .allowedHeader("X-Requested-With")); }
Example #11
Source File: MyCustomRouterConfig.java From vxms with Apache License 2.0 | 5 votes |
public void corsHandler(Router router) { router .route() .handler( CorsHandler.create("*") .allowedMethod(io.vertx.core.http.HttpMethod.GET) .allowedMethod(io.vertx.core.http.HttpMethod.POST) .allowedMethod(io.vertx.core.http.HttpMethod.OPTIONS) .allowedMethod(io.vertx.core.http.HttpMethod.PUT) .allowedMethod(io.vertx.core.http.HttpMethod.DELETE) .allowedHeader("Content-Type") .allowedHeader("X-Requested-With")); }
Example #12
Source File: CookieRouterConfig.java From vxms with Apache License 2.0 | 5 votes |
public void cookieHandler(Router router) { router .route() .handler( CorsHandler.create("127.0.0.1") .allowedMethod(io.vertx.core.http.HttpMethod.GET) .allowedMethod(io.vertx.core.http.HttpMethod.POST) .allowedMethod(io.vertx.core.http.HttpMethod.OPTIONS) .allowedMethod(io.vertx.core.http.HttpMethod.PUT) .allowedMethod(io.vertx.core.http.HttpMethod.DELETE) .allowedHeader("Content-Type") .allowedHeader("X-Requested-With")); }
Example #13
Source File: RestrictedCorsRouterConfig3.java From vxms with Apache License 2.0 | 5 votes |
public void corsHandler(Router router) { router .route("/stringGETResponseSyncAsync*") .handler( CorsHandler.create("http://example.com") .allowedMethod(io.vertx.core.http.HttpMethod.GET) .allowedMethod(io.vertx.core.http.HttpMethod.POST) .allowedMethod(io.vertx.core.http.HttpMethod.OPTIONS) .allowedMethod(io.vertx.core.http.HttpMethod.PUT) .allowedMethod(io.vertx.core.http.HttpMethod.DELETE) .allowedHeader("Content-Type") .allowedHeader("X-Requested-With")); }
Example #14
Source File: HttpServer.java From Lealone-Plugins with Apache License 2.0 | 5 votes |
private void startVertxHttpServer() { if (apiPath == null) apiPath = "/_lealone_sockjs_/*"; final String path = apiPath; VertxOptions opt = new VertxOptions(); opt.setBlockedThreadCheckInterval(Integer.MAX_VALUE); vertx = Vertx.vertx(opt); vertxHttpServer = vertx.createHttpServer(); Router router = Router.router(vertx); String syncRequestUrl = "/_lealone_sync_request_"; router.post(syncRequestUrl).handler(BodyHandler.create()); router.post(syncRequestUrl).handler(routingContext -> { String command = routingContext.request().params().get("command"); Buffer result = ServiceHandler.handle(routingContext, command); routingContext.request().response().headers().set("Access-Control-Allow-Origin", "*"); routingContext.request().response().end(result); }); router.route().handler(CorsHandler.create("*").allowedMethod(HttpMethod.GET).allowedMethod(HttpMethod.POST)); setSockJSHandler(router); // ζΎε¨ζε setStaticHandler(router); vertxHttpServer.requestHandler(router::handle).listen(port, host, res -> { if (res.succeeded()) { logger.info("web root: " + webRoot); logger.info("sockjs path: " + path); logger.info("http server is now listening on port: " + vertxHttpServer.actualPort()); } else { logger.error("failed to bind " + port + " port!", res.cause()); } }); }
Example #15
Source File: ApolloTestsServer.java From vertx-web with Apache License 2.0 | 5 votes |
@Override public void start(Promise<Void> startPromise) throws Exception { Router router = Router.router(vertx); router.route().handler(CorsHandler.create("*").allowedMethod(GET).allowedMethod(POST)); router.route().handler(BodyHandler.create()); router.route("/graphql").handler(ApolloWSHandler.create(setupWsGraphQL())); GraphQLHandlerOptions graphQLHandlerOptions = new GraphQLHandlerOptions() .setRequestBatchingEnabled(true) .setRequestMultipartEnabled(true); router.route("/graphql").handler(GraphQLHandler.create(setupGraphQL(), graphQLHandlerOptions)); HttpServerOptions httpServerOptions = new HttpServerOptions().addWebSocketSubProtocol("graphql-ws"); vertx.createHttpServer(httpServerOptions) .requestHandler(router) .listen(8080) .<Void>mapEmpty() .onComplete(ar -> { if (ar.succeeded()) { System.out.println("Apollo tests server started"); } startPromise.handle(ar); }); }
Example #16
Source File: CorsHandlerImpl.java From vertx-web with Apache License 2.0 | 5 votes |
@Override public CorsHandler allowedMethods(Set<HttpMethod> methods) { for (HttpMethod method : methods) { allowedMethods.add(method.name()); } allowedMethodsString = String.join(",", allowedMethods); return this; }
Example #17
Source File: MainVerticle.java From nassh-relay with GNU General Public License v2.0 | 5 votes |
@Override public void start(final Promise<Void> startPromise) { final JsonObject webserviceConfig = config().getJsonObject("webservice"); if (webserviceConfig.containsKey("hostname")) { logger.warn("webservice.hostname will be deprecated in future releases, please use webservice.host instead"); webserviceConfig.put("host", webserviceConfig.getString("hostname", webserviceConfig.getString("host"))); } final HttpServerOptions options = new HttpServerOptions(webserviceConfig); if (options.isSsl() && options.getKeyCertOptions() == null) { logger.warn("no certificate configured, creating self-signed"); final SelfSignedCertificate certificate = SelfSignedCertificate.create(); options.setKeyCertOptions(certificate.keyCertOptions()); options.setTrustOptions(certificate.trustOptions()); } server = vertx.createHttpServer(options); final Router router = Router.router(vertx); router.route().handler(CorsHandler .create(".*") .allowCredentials(true) ); router.get("/cookie").handler(new CookieHandler(config().getJsonObject("application").copy().put("auth", config().getJsonObject("google-sso")))); router.post("/cookie").handler(new CookiePostHandler(vertx, new JsonObject().put("auth", config().getJsonObject("google-sso")))); router.get("/proxy").handler(new ProxyHandler(vertx, config())); router.get("/write").handler(new WriteHandler(vertx)); router.get("/read").handler(new ReadHandler(vertx)); server.requestHandler(router); server.webSocketHandler(new ConnectHandler(vertx)); server.listen(result -> { if (result.succeeded()) { logger.info("nassh-relay listening on port " + result.result().actualPort()); startPromise.complete(); } else { startPromise.fail(result.cause()); } } ); }
Example #18
Source File: CorsHelper.java From okapi with Apache License 2.0 | 5 votes |
/** * Add CORS handler to {@link Router}. * * @param router - {@link Router} */ public static void addCorsHandler(Router router) { router.routeWithRegex("^/_/invoke/tenant/[^/ ]+/.*").handler(ctx -> { ctx.data().put(CHECK_DELEGATE_CORS, true); ctx.next(); }); router.route().handler(ctx -> { if (ctx.data().containsKey(DELEGATE_CORS)) { ctx.next(); } else { CorsHandler.create("*") .allowedMethod(HttpMethod.PUT) .allowedMethod(HttpMethod.PATCH) .allowedMethod(HttpMethod.DELETE) .allowedMethod(HttpMethod.GET) .allowedMethod(HttpMethod.POST) .allowedHeader(HttpHeaders.CONTENT_TYPE.toString()) .allowedHeader(XOkapiHeaders.TENANT) .allowedHeader(XOkapiHeaders.TOKEN) .allowedHeader(XOkapiHeaders.AUTHORIZATION) .allowedHeader(XOkapiHeaders.REQUEST_ID) //expose response headers .allowedHeader(XOkapiHeaders.MODULE_ID) .exposedHeader(HttpHeaders.LOCATION.toString()) .exposedHeader(XOkapiHeaders.TRACE) .exposedHeader(XOkapiHeaders.TOKEN) .exposedHeader(XOkapiHeaders.AUTHORIZATION) .exposedHeader(XOkapiHeaders.REQUEST_ID) .exposedHeader(XOkapiHeaders.MODULE_ID).handle(ctx); } }); }
Example #19
Source File: XYZHubRESTVerticle.java From xyz-hub with Apache License 2.0 | 5 votes |
/** * Add support for cross origin requests. */ private CorsHandler createCorsHandler() { CorsHandler cors = CorsHandler.create(".*").allowCredentials(true); allowMethods.forEach(cors::allowedMethod); allowHeaders.stream().map(String::valueOf).forEach(cors::allowedHeader); exposeHeaders.stream().map(String::valueOf).forEach(cors::exposedHeader); return cors; }
Example #20
Source File: WebConfiguration.java From prebid-server-java with Apache License 2.0 | 5 votes |
@Bean CorsHandler corsHandler() { return CorsHandler.create(".*") .allowCredentials(true) .allowedHeaders(new HashSet<>(Arrays.asList( HttpUtil.ORIGIN_HEADER.toString(), HttpUtil.ACCEPT_HEADER.toString(), HttpUtil.CONTENT_TYPE_HEADER.toString(), HttpUtil.X_REQUESTED_WITH_HEADER.toString()))) .allowedMethods(new HashSet<>(Arrays.asList(HttpMethod.GET, HttpMethod.POST, HttpMethod.HEAD, HttpMethod.OPTIONS))); }
Example #21
Source File: WebVerticle.java From vertx-starter with Apache License 2.0 | 5 votes |
@Override public void start(Promise<Void> startPromise) { vertx.eventBus().registerDefaultCodec(VertxProject.class, new VertxProjectCodec()); Router router = Router.router(vertx); CorsHandler corsHandler = CorsHandler.create("*") .allowedMethod(HttpMethod.GET) .allowedMethod(HttpMethod.POST) .allowedHeader("Content-Type") .allowedHeader("Accept"); router.route().handler(corsHandler); router.get("/metadata").handler(metadataHandler); router.get("/starter.*").handler(validationHandler).handler(generationHandler); router.route().handler(StaticHandler.create()); int port = config().getInteger(HTTP_PORT, 8080); vertx.createHttpServer() .requestHandler(router) .listen(port, ar -> { if (ar.failed()) { log.error("Fail to start {}", WebVerticle.class.getSimpleName(), ar.cause()); startPromise.fail(ar.cause()); } else { log.info("\n----------------------------------------------------------\n\t" + "{} is running! Access URLs:\n\t" + "Local: \t\thttp://localhost:{}\n" + "----------------------------------------------------------", WebVerticle.class.getSimpleName(), port); startPromise.complete(); } }); }
Example #22
Source File: PluginManagerVerticle.java From dfx with Apache License 2.0 | 5 votes |
private static void addCorsHandler(Router router, CorsConfig corsConfig) { if (corsConfig != null) { CorsHandler corsHandler = CorsHandler.create(corsConfig.getAllowedOriginPattern()); if (corsConfig.getAllowedMethods() != null) { corsHandler.allowedMethods(corsConfig.getAllowedMethods()); } if (corsConfig.getAllowCredentials() != null) { corsHandler.allowCredentials(corsConfig.getAllowCredentials()); } if (corsConfig.getAllowedHeaders() != null) { corsHandler.allowedHeaders(corsConfig.getAllowedHeaders()); } if (corsConfig.getExposedHeaders() != null) { corsHandler.exposedHeaders(corsConfig.getExposedHeaders()); } if (corsConfig.getMaxAgeSeconds() != null) { corsHandler.maxAgeSeconds(corsConfig.getMaxAgeSeconds()); } router.route().handler(corsHandler); } }
Example #23
Source File: RestServerVerticle.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
/** * Support CORS */ void mountCorsHandler(Router mainRouter) { if (!TransportConfig.isCorsEnabled()) { return; } CorsHandler corsHandler = getCorsHandler(TransportConfig.getCorsAllowedOrigin()); // Access-Control-Allow-Credentials corsHandler.allowCredentials(TransportConfig.isCorsAllowCredentials()); // Access-Control-Allow-Headers corsHandler.allowedHeaders(TransportConfig.getCorsAllowedHeaders()); // Access-Control-Allow-Methods Set<String> allowedMethods = TransportConfig.getCorsAllowedMethods(); for (String method : allowedMethods) { corsHandler.allowedMethod(HttpMethod.valueOf(method)); } // Access-Control-Expose-Headers corsHandler.exposedHeaders(TransportConfig.getCorsExposedHeaders()); // Access-Control-Max-Age int maxAge = TransportConfig.getCorsMaxAge(); if (maxAge >= 0) { corsHandler.maxAgeSeconds(maxAge); } LOGGER.info("mount CorsHandler"); mainRouter.route().handler(corsHandler); }
Example #24
Source File: SigfoxProtocolAdapter.java From hono with Eclipse Public License 2.0 | 5 votes |
private Handler<RoutingContext> dataCorsHandler() { return CorsHandler.create(getConfig().getCorsAllowedOrigin()) .allowedMethod(HttpMethod.GET) .allowedHeader(Constants.HEADER_TIME_TILL_DISCONNECT) .allowedHeader(HttpHeaders.AUTHORIZATION.toString()) .allowedHeader(HttpHeaders.CONTENT_TYPE.toString()) .exposedHeader(Constants.HEADER_COMMAND) .exposedHeader(Constants.HEADER_COMMAND_REQUEST_ID); }
Example #25
Source File: HelloworldVerticle.java From kubernetes-lab with Apache License 2.0 | 5 votes |
@Override public void start() throws Exception { Router router = Router.router(vertx); //Config CORS router.route().handler(CorsHandler.create("*") .allowedMethod(HttpMethod.GET) .allowedHeader("Content-Type")); // hello endpoint router.get("/api/hello/:name").handler(ctx -> { ctx.response().end(hello(ctx.request().getParam("name"))); }); vertx.createHttpServer().requestHandler(router::accept).listen(8080); }
Example #26
Source File: CorsHandlerImpl.java From vertx-web with Apache License 2.0 | 4 votes |
@Override public CorsHandler exposedHeader(String headerName) { exposedHeaders.add(headerName); exposedHeadersString = String.join(",", exposedHeaders); return this; }
Example #27
Source File: ServerConfig.java From festival with Apache License 2.0 | 4 votes |
@Singleton @Named public CorsHandler corsHandler() { return CorsHandler.create("vertx.io") .allowedMethod(HttpMethod.GET); }
Example #28
Source File: CorsHandlerImpl.java From vertx-web with Apache License 2.0 | 4 votes |
@Override public CorsHandler allowedHeader(String headerName) { allowedHeaders.add(headerName); allowedHeadersString = String.join(",", allowedHeaders); return this; }
Example #29
Source File: CorsHandlerImpl.java From vertx-web with Apache License 2.0 | 4 votes |
@Override public CorsHandler allowedHeaders(Set<String> headerNames) { allowedHeaders.addAll(headerNames); allowedHeadersString = String.join(",", allowedHeaders); return this; }
Example #30
Source File: RestServerVerticle.java From servicecomb-java-chassis with Apache License 2.0 | 4 votes |
private CorsHandler getCorsHandler(String corsAllowedOrigin) { return CorsHandler.create(corsAllowedOrigin); }