io.vertx.ext.web.sstore.LocalSessionStore Java Examples
The following examples show how to use
io.vertx.ext.web.sstore.LocalSessionStore.
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: ChainAuthHandlerTest.java From vertx-web with Apache License 2.0 | 6 votes |
@Test public void testWithBasicAuthAsLastHandlerInChain() throws Exception { // after removing the RedirectAuthHandler, we check if the chain correctly returns the WWW-Authenticate Header, since now the BasicAuthHandler is the last handler in the chain router.clear(); // create a chain chain = ChainAuthHandler.any() .add(JWTAuthHandler.create(null)) .add(BasicAuthHandler.create(authProvider)); router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx))); router.route().handler(chain); router.route().handler(ctx -> ctx.response().end()); testRequest(HttpMethod.GET, "/", req -> req.putHeader("Authorization", "Basic dGltOmRlbGljaW91czpzYXVzYWdlcX=="), resp -> assertEquals("Basic realm=\"vertx-web\"", resp.getHeader("WWW-Authenticate")),401, "Unauthorized", "Unauthorized"); }
Example #2
Source File: ChainAuthHandlerTest.java From vertx-web with Apache License 2.0 | 6 votes |
@Override public void setUp() throws Exception { super.setUp(); authProvider = PropertyFileAuthentication.create(vertx, "login/loginusers.properties"); AuthenticationHandler redirectAuthHandler = RedirectAuthHandler.create(authProvider); // create a chain chain = ChainAuthHandler.any() .add(JWTAuthHandler.create(null)) .add(BasicAuthHandler.create(authProvider)) .add(redirectAuthHandler); router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx))); router.route().handler(chain); router.route().handler(ctx -> ctx.response().end()); }
Example #3
Source File: RedirectAuthHandlerTest.java From vertx-web with Apache License 2.0 | 6 votes |
private void doLoginCommon(Handler<RoutingContext> handler) throws Exception { router.route().handler(BodyHandler.create()); SessionStore store = LocalSessionStore.create(vertx); router.route().handler(SessionHandler.create(store)); AuthenticationHandler authHandler = RedirectAuthHandler.create(authProvider); router.route("/protected/*").handler(authHandler); router.route("/protected/somepage").handler(handler); String loginHTML = createloginHTML(); router.route("/loginpage").handler(rc -> rc.response().putHeader("content-type", "text/html").end(loginHTML)); if (formLoginHandler == null) { formLoginHandler = FormLoginHandler.create(authProvider); } router.route("/login").handler(formLoginHandler); testRequest(HttpMethod.GET, "/protected/somepage", null, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertEquals("/loginpage", location); String setCookie = resp.headers().get("set-cookie"); assertNotNull(setCookie); sessionCookie.set(setCookie); }, 302, "Found", null); testRequest(HttpMethod.GET, "/loginpage", req -> req.putHeader("cookie", sessionCookie.get()), resp -> { }, 200, "OK", loginHTML); }
Example #4
Source File: ChainAuthMixHandlerTest.java From vertx-web with Apache License 2.0 | 6 votes |
@Test public void testFailOrFailOrSuccess() throws Exception { // (failure OR (failure OR success)) ChainAuthHandler chain = ChainAuthHandler.any() .add(failure) .add( ChainAuthHandler.any() .add(failure) .add(success) ); router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx))); router.route().handler(chain); router.route().handler(ctx -> ctx.response().end()); testRequest(HttpMethod.GET, "/", 200, "OK"); }
Example #5
Source File: ChainAuthHandlerAndTest.java From vertx-web with Apache License 2.0 | 6 votes |
@Test public void testWithBasicAuthAsLastHandlerInChain() throws Exception { // after removing the RedirectAuthHandler, we check if the chain correctly returns the WWW-Authenticate Header, since now the BasicAuthHandler is the last handler in the chain router.clear(); // create a chain chain = ChainAuthHandler.all() .add(JWTAuthHandler.create(null)) .add(BasicAuthHandler.create(authProvider)); router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx))); router.route().handler(chain); router.route().handler(ctx -> ctx.response().end()); testRequest(HttpMethod.GET, "/", req -> req.putHeader("Authorization", "Basic dGltOmRlbGljaW91czpzYXVzYWdlcX=="), resp -> assertEquals("Basic realm=\"vertx-web\"", resp.getHeader("WWW-Authenticate")),401, "Unauthorized", "Unauthorized"); }
Example #6
Source File: ChainAuthHandlerAndTest.java From vertx-web with Apache License 2.0 | 6 votes |
@Override public void setUp() throws Exception { super.setUp(); authProvider = PropertyFileAuthentication.create(vertx, "login/loginusers.properties"); AuthenticationHandler redirectAuthHandler = RedirectAuthHandler.create(authProvider); // create a chain chain = ChainAuthHandler.all() .add(JWTAuthHandler.create(null)) .add(BasicAuthHandler.create(authProvider)) .add(redirectAuthHandler); router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx))); router.route().handler(chain); router.route().handler(ctx -> ctx.response().end()); }
Example #7
Source File: ChainAuthMixHandlerTest.java From vertx-web with Apache License 2.0 | 6 votes |
@Test public void testFailOrSuccessAndFail() throws Exception { // (failure OR (sucess AND failure)) ChainAuthHandler chain = ChainAuthHandler.any() .add(failure) .add( ChainAuthHandler.all() .add(success) .add(failure) ); router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx))); router.route().handler(chain); router.route().handler(ctx -> ctx.response().end()); testRequest(HttpMethod.GET, "/", 401, "Unauthorized"); }
Example #8
Source File: MVCRoute.java From nubes with Apache License 2.0 | 6 votes |
public void attachHandlersToRouter(Router router) { config.forEachGlobalHandler(handler -> router.route(httpMethod, path).handler(handler)); final Vertx vertx = config.getVertx(); if (authHandler != null) { attachAuthHandler(router, vertx); } else if (usesSession) { router.route(httpMethod, path).handler(SessionHandler.create(LocalSessionStore.create(vertx))); } handlers.forEach(handler -> router.route(httpMethod, path).handler(handler) ); attachPreProcessingHandlers(router); boolean hasPostProcessors = redirectRoute != null || postInterceptor != null || !afterFilters.isEmpty()|| !processors.isEmpty(); setHandler(router, mainHandler, hasPostProcessors); if (redirectRoute != null) { // intercepted -> redirected => do not call post processing handlers router.route(httpMethod, path).handler(ctx -> ctx.reroute(redirectRoute.method(), redirectRoute.path()) ); } attachPostProcessingHandlers(router); }
Example #9
Source File: WebExamples.java From vertx-web with Apache License 2.0 | 6 votes |
public void example31(Vertx vertx) { // Create a local session store using defaults SessionStore store1 = LocalSessionStore.create(vertx); // Create a local session store specifying the local shared map name to use // This might be useful if you have more than one application in the same // Vert.x instance and want to use different maps for different applications SessionStore store2 = LocalSessionStore.create( vertx, "myapp3.sessionmap"); // Create a local session store specifying the local shared map name to use and // setting the reaper interval for expired sessions to 10 seconds SessionStore store3 = LocalSessionStore.create( vertx, "myapp3.sessionmap", 10000); }
Example #10
Source File: MVCRoute.java From nubes with Apache License 2.0 | 5 votes |
private void attachAuthHandler(Router router, Vertx vertx) { final AuthProvider authProvider = config.getAuthProvider(); router.route(httpMethod, path).handler(CookieHandler.create()); router.route(httpMethod, path).handler(UserSessionHandler.create(authProvider)); router.route(httpMethod, path).handler(SessionHandler.create(LocalSessionStore.create(vertx))); router.route(httpMethod, path).handler(authHandler); if (loginRedirect != null && !"".equals(loginRedirect)) { router.post(loginRedirect).handler(CookieHandler.create()); router.post(loginRedirect).handler(BodyHandler.create()); router.post(loginRedirect).handler(UserSessionHandler.create(authProvider)); router.post(loginRedirect).handler(SessionHandler.create(LocalSessionStore.create(vertx))); router.post(loginRedirect).handler(FormLoginHandler.create(authProvider)); } }
Example #11
Source File: WebExamples.java From vertx-web with Apache License 2.0 | 5 votes |
public void example75(Vertx vertx, Router router, CredentialStore authStore) { // create the webauthn security object WebAuthn webAuthn = WebAuthn.create( vertx, new WebAuthnOptions() .setOrigin("https://192.168.178.74.xip.io:8443") .setRelayParty(new RelayParty().setName("Vert.x WebAuthN Demo")) // What kind of authentication do you want? do you care? // if you care you can specify it (choose one of the 2) // # security keys .setAuthenticatorAttachment(AuthenticatorAttachment.CROSS_PLATFORM) .setRequireResidentKey(false) // # fingerprint .setAuthenticatorAttachment(AuthenticatorAttachment.PLATFORM) .setRequireResidentKey(false) .setUserVerification(UserVerification.REQUIRED), // where to load the credentials from? authStore); // parse the BODY router.post() .handler(BodyHandler.create()); // add a session handler router.route() .handler(SessionHandler .create(LocalSessionStore.create(vertx))); // security handler WebAuthnHandler webAuthNHandler = WebAuthnHandler.create(webAuthn) // required callback .setupCallback(router.post("/webauthn/response")) // optional register callback .setupCredentialsCreateCallback(router.post("/webauthn/register")) // optional login callback .setupCredentialsGetCallback(router.post("/webauthn/login")); // secure the remaining routes router.route().handler(webAuthNHandler); }
Example #12
Source File: WebExamples.java From vertx-web with Apache License 2.0 | 5 votes |
public void example39(Vertx vertx, AuthenticationProvider authProvider, Router router) { router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx))); // All requests to paths starting with '/private/' will be protected router .route("/private/*") .handler(RedirectAuthHandler.create(authProvider)); // Handle the actual login // One of your pages must POST form login data router.post("/login").handler(FormLoginHandler.create(authProvider)); // Set a static server to serve static resources, e.g. the login page router.route().handler(StaticHandler.create()); router .route("/someotherpath") .handler(ctx -> { // This will be public access - no login required }); router .route("/private/somepath") .handler(ctx -> { // This will require a login // This will have the value true boolean isAuthenticated = ctx.user() != null; }); }
Example #13
Source File: SessionHandlerTestBase.java From vertx-web with Apache License 2.0 | 5 votes |
@Test public void testSessionExpires() throws Exception { long timeout = 1000; router.route().handler(SessionHandler.create(store).setSessionTimeout(timeout)); AtomicReference<String> rid = new AtomicReference<>(); AtomicInteger requestCount = new AtomicInteger(); router.route().handler(rc -> { Session sess = rc.session(); assertNotNull(sess); assertTrue(System.currentTimeMillis() - sess.lastAccessed() < 500); assertNotNull(sess.id()); switch (requestCount.get()) { case 0: sess.put("foo", "bar"); break; case 1: assertFalse(rid.get().equals(sess.id())); // New session assertNull(sess.get("foo")); break; } rid.set(sess.id()); requestCount.incrementAndGet(); rc.response().end(); }); AtomicReference<String> rSetCookie = new AtomicReference<>(); testRequest(HttpMethod.GET, "/", null, resp -> { String setCookie = resp.headers().get("set-cookie"); rSetCookie.set(setCookie); }, 200, "OK", null); Thread.sleep(2 * (LocalSessionStore.DEFAULT_REAPER_INTERVAL + timeout)); testRequest(HttpMethod.GET, "/", req -> req.putHeader("cookie", rSetCookie.get()), null, 200, "OK", null); waitUntil(() -> testSessionBlocking(rid.get(), Objects::nonNull)); Thread.sleep(2 * (LocalSessionStore.DEFAULT_REAPER_INTERVAL + timeout)); waitUntil(() -> testSessionBlocking(rid.get(), Objects::isNull)); }
Example #14
Source File: CookielessSessionHandlerTestBase.java From vertx-web with Apache License 2.0 | 5 votes |
@Test public void testSessionExpires() throws Exception { long timeout = 1000; router.route().handler(SessionHandler.create(store).setSessionTimeout(timeout).setCookieless(true)); AtomicReference<String> rid = new AtomicReference<>(); AtomicInteger requestCount = new AtomicInteger(); router.route().handler(rc -> { Session sess = rc.session(); assertNotNull(sess); assertTrue(System.currentTimeMillis() - sess.lastAccessed() < 500); assertNotNull(sess.id()); switch (requestCount.get()) { case 0: sess.put("foo", "bar"); break; case 1: assertFalse(rid.get().equals(sess.id())); // New session assertNull(sess.get("foo")); break; } rid.set(sess.id()); requestCount.incrementAndGet(); rc.response().end(); }); testRequest(HttpMethod.GET, "/", 200, "OK"); Thread.sleep(2 * (LocalSessionStore.DEFAULT_REAPER_INTERVAL + timeout)); testRequest(HttpMethod.GET, "/(" + rid.get() + ")", 200, "OK"); waitUntil(() -> testSessionBlocking(rid.get(), Objects::nonNull)); Thread.sleep(2 * (LocalSessionStore.DEFAULT_REAPER_INTERVAL + timeout)); waitUntil(() -> testSessionBlocking(rid.get(), Objects::isNull)); }
Example #15
Source File: SockJSTestBase.java From vertx-web with Apache License 2.0 | 5 votes |
void startServers() throws Exception { CountDownLatch latch = new CountDownLatch(1); vertx.deployVerticle(() -> new AbstractVerticle() { @Override public void start(Promise<Void> startFuture) throws Exception { Router router = Router.router(vertx); router.route() .handler(SessionHandler.create(LocalSessionStore.create(vertx)) .setNagHttps(false) .setSessionTimeout(60 * 60 * 1000)); if (preSockJSHandlerSetup != null) { preSockJSHandlerSetup.accept(router); } SockJSHandlerOptions options = new SockJSHandlerOptions().setHeartbeatInterval(2000); SockJSHandler sockJSHandler = SockJSHandler.create(vertx, options); sockJSHandler.socketHandler(socketHandler.get()); router.route("/test/*").handler(sockJSHandler); vertx.createHttpServer(new HttpServerOptions().setPort(8080).setHost("localhost")) .requestHandler(router) .listen(ar -> { if (ar.succeeded()) { startFuture.complete(); } else { startFuture.fail(ar.cause()); } }); } }, new DeploymentOptions().setInstances(numServers), onSuccess(id -> latch.countDown())); awaitLatch(latch); }
Example #16
Source File: EventbusBridgeTest.java From vertx-web with Apache License 2.0 | 5 votes |
@Test public void testSendRequiresAuthorityHasAuthority() throws Exception { sockJSHandler.bridge(PropertyFileAuthorization.create(vertx, "login/loginusers.properties"), defaultOptions.addInboundPermitted(new PermittedOptions().setAddress(addr).setRequiredAuthority("bang_sticks")), null); router.clear(); SessionStore store = LocalSessionStore.create(vertx); router.route().handler(SessionHandler.create(store)); AuthenticationProvider authProvider = PropertyFileAuthentication.create(vertx, "login/loginusers.properties"); addLoginHandler(router, authProvider); router.route("/eventbus/*").handler(sockJSHandler); testSend("foo"); }
Example #17
Source File: RouteWithSessionTest.java From rest.vertx with Apache License 2.0 | 5 votes |
@BeforeAll static void start() { before(); Router router = Router.router(vertx); SessionHandler handler = SessionHandler.create(LocalSessionStore.create(vertx)); router.route().handler(handler); RestRouter.register(router, TestSessionRest.class); vertx.createHttpServer() .requestHandler(router) .listen(PORT); }
Example #18
Source File: EventbusBridgeTest.java From vertx-web with Apache License 2.0 | 5 votes |
@Test public void testSendRequiresAuthorityHasnotAuthority() throws Exception { sockJSHandler.bridge(defaultOptions.addInboundPermitted(new PermittedOptions().setAddress(addr).setRequiredAuthority("pick_nose"))); router.clear(); SessionStore store = LocalSessionStore.create(vertx); router.route().handler(SessionHandler.create(store)); AuthenticationProvider authProvider = PropertyFileAuthentication.create(vertx, "login/loginusers.properties"); addLoginHandler(router, authProvider); router.route("/eventbus/*").handler(sockJSHandler); testError(new JsonObject().put("type", "send").put("address", addr).put("body", "foo"), "access_denied"); }
Example #19
Source File: SessionManager.java From festival with Apache License 2.0 | 5 votes |
private SessionStore getOrCreateSessionStore() throws BeansException { SessionStore sessionStore; try { sessionStore = beanFactory.getBean(SessionStore.class); } catch (NoSuchBeanException e) { sessionStore = LocalSessionStore.create(vertx); } return sessionStore; }
Example #20
Source File: VertxWrappedSessionWithLocalSessionStoreUT.java From vertx-vaadin with MIT License | 4 votes |
@Before public void setUp(TestContext context) { vertx = Vertx.vertx(); localSessionStore = LocalSessionStore.create(vertx); }
Example #21
Source File: AuthHandlerTestBase.java From vertx-web with Apache License 2.0 | 4 votes |
protected SessionStore getSessionStore() { return LocalSessionStore.create(vertx); }
Example #22
Source File: CookielessSessionHandlerTestBase.java From vertx-web with Apache License 2.0 | 4 votes |
@Override public void setUp() throws Exception { super.setUp(); store = LocalSessionStore.create(vertx); }
Example #23
Source File: WebExamples.java From vertx-web with Apache License 2.0 | 4 votes |
public void example62(Vertx vertx, Router router) { // To simplify the development of the web components // we use a Router to route all HTTP requests // to organize our code in a reusable way. // Simple auth service which uses a GitHub to // authenticate the user OAuth2Auth authProvider = GithubAuth .create(vertx, "CLIENTID", "CLIENT SECRET"); // We need a user session handler too to make sure // the user is stored in the session between requests router.route() .handler(SessionHandler.create(LocalSessionStore.create(vertx))); // we now protect the resource under the path "/protected" router.route("/protected").handler( OAuth2AuthHandler.create(vertx, authProvider) // we now configure the oauth2 handler, it will // setup the callback handler // as expected by your oauth2 provider. .setupCallback(router.route("/callback")) // for this resource we require that users have // the authority to retrieve the user emails .withScope("user:email") ); // Entry point to the application, this will render // a custom template. router.get("/").handler(ctx -> ctx.response() .putHeader("Content-Type", "text/html") .end( "<html>\n" + " <body>\n" + " <p>\n" + " Well, hello there!\n" + " </p>\n" + " <p>\n" + " We're going to the protected resource, if there is no\n" + " user in the session we will talk to the GitHub API. Ready?\n" + " <a href=\"/protected\">Click here</a> to begin!</a>\n" + " </p>\n" + " <p>\n" + " <b>If that link doesn't work</b>, remember to provide your\n" + " own <a href=\"https://github.com/settings/applications/new\">\n" + " Client ID</a>!\n" + " </p>\n" + " </body>\n" + "</html>")); // The protected resource router.get("/protected").handler(ctx -> { // at this moment your user object should contain the info // from the Oauth2 response, since this is a protected resource // as specified above in the handler config the user object is never null User user = ctx.user(); // just dump it to the client for demo purposes ctx.response().end(user.toString()); }); }
Example #24
Source File: WebExamples.java From vertx-web with Apache License 2.0 | 4 votes |
public void example38(Vertx vertx, AuthenticationProvider authProvider, Router router) { router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx))); AuthenticationHandler basicAuthHandler = BasicAuthHandler.create(authProvider); // All requests to paths starting with '/private/' will be protected router.route("/private/*").handler(basicAuthHandler); router.route("/someotherpath").handler(ctx -> { // This will be public access - no login required }); router.route("/private/somepath").handler(ctx -> { // This will require a login // This will have the value true boolean isAuthenticated = ctx.user() != null; }); }
Example #25
Source File: CustomRouterConfig.java From vxms with Apache License 2.0 | 4 votes |
public void sessionHandler(Vertx vertx, Router router) { router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx))); }
Example #26
Source File: RestAPIVerticle.java From vertx-blueprint-microservice with Apache License 2.0 | 4 votes |
/** * Enable local session storage in requests. * * @param router router instance */ protected void enableLocalSession(Router router) { router.route().handler(CookieHandler.create()); router.route().handler(SessionHandler.create( LocalSessionStore.create(vertx, "shopping.user.session"))); }
Example #27
Source File: CloudIamAuthNexusProxyVerticle.java From nexus-proxy with Apache License 2.0 | 4 votes |
@Override protected void preconfigureRouting(final Router router) { router.route().handler(CookieHandler.create()); router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)).setSessionTimeout(SESSION_TTL)); }
Example #28
Source File: ClientVerticle.java From VX-API-Gateway with MIT License | 4 votes |
@Override public void start(Promise<Void> fut) throws Exception { LOG.info("start Client Verticle ..."); thisVertxName = System.getProperty("thisVertxName", "VX-API"); Router router = Router.router(vertx); router.route().handler(FaviconHandler.create(getFaviconPath())); router.route().handler(BodyHandler.create().setUploadsDirectory(getUploadsDirectory())); if (vertx.isClustered()) { router.route().handler( SessionHandler.create(ClusteredSessionStore.create(vertx)).setSessionCookieName(VxApiGatewayAttribute.SESSION_COOKIE_NAME)); } else { router.route() .handler(SessionHandler.create(LocalSessionStore.create(vertx)).setSessionCookieName(VxApiGatewayAttribute.SESSION_COOKIE_NAME)); } // 通过html的方式管理应用网关 // TemplateEngine create = FreeMarkerTemplateEngine.create(vertx); // TemplateHandler tempHandler = TemplateHandler.create(create, getTemplateRoot(), CONTENT_VALUE_HTML_UTF8); TemplateHandler tempHandler = new FreeMarkerTemplateHander(vertx, getTemplateRoot(), CONTENT_VALUE_HTML_UTF8); router.getWithRegex(".+\\.ftl").handler(tempHandler); // 权限相关 router.route("/static/*").handler(VxApiClientStaticAuth.create()); router.route("/static/*").handler(this::staticAuth); router.route("/loginOut").handler(this::loginOut); router.route("/static/CreateAPI.html").handler(this::staticAPI); router.route("/static/CreateAPP.html").handler(this::staticAPP); router.route("/static/*").handler(StaticHandler.create(getStaticRoot())); // 查看系统信息 router.route("/static/sysInfo").handler(this::sysInfo); router.route("/static/sysReplaceIpList").handler(this::sysReplaceIpList); // Application相关 router.route("/static/findAPP").handler(this::findAPP); router.route("/static/getAPP/:name").handler(this::getAPP); router.route("/static/addAPP").handler(this::addAPP); router.route("/static/delAPP/:name").handler(this::delAPP); router.route("/static/updtAPP/:name").handler(this::loadUpdtAPP); router.route("/static/updtAPP").handler(this::updtAPP); router.route("/static/deployAPP/:name").handler(this::deployAPP); router.route("/static/unDeployAPP/:name").handler(this::unDeployAPP); // API相关 router.route("/static/findAPI/:name").handler(this::findAPI); router.route("/static/getAPI/:name").handler(this::getAPI); router.route("/static/addAPI").handler(this::addAPI); router.route("/static/updtAPI/:name").handler(this::loadUpdtAPI); router.route("/static/updtAPI").handler(this::updtAPI); router.route("/static/delAPI/:appName/:apiName").handler(this::delAPI); router.route("/static/startAllAPI/:appName").handler(this::startAllAPI); router.route("/static/startAPI/:apiName").handler(this::startAPI); router.route("/static/stopAPI/:appName/:apiName").handler(this::stopAPI); router.route("/static/trackInfo/:appName/:apiName").handler(this::getTrackInfo); // 欢迎页 router.route("/").handler(this::welcome); vertx.createHttpServer().requestHandler(router).listen(config().getInteger("clientPort", 5256), res -> { if (res.succeeded()) { LOG.info("start Clinet Verticle successful"); fut.complete(); } else { LOG.info("start Clinet Verticle unsuccessful"); fut.fail(res.cause()); } }); }
Example #29
Source File: VxApiApplication.java From VX-API-Gateway with MIT License | 4 votes |
/** * 创建https服务器 * * @param createHttp */ public void createHttpsServer(Handler<AsyncResult<Void>> createHttps) { this.httpsRouter = Router.router(vertx); httpsRouter.route().handler(this::filterBlackIP); httpsRouter.route().handler(CookieHandler.create()); SessionStore sessionStore = null; if (vertx.isClustered()) { sessionStore = ClusteredSessionStore.create(vertx); } else { sessionStore = LocalSessionStore.create(vertx); } SessionHandler sessionHandler = SessionHandler.create(sessionStore); sessionHandler.setSessionCookieName(appOption.getSessionCookieName()); sessionHandler.setSessionTimeout(appOption.getSessionTimeOut()); httpsRouter.route().handler(sessionHandler); // 跨域处理 if (corsOptions != null) { CorsHandler corsHandler = CorsHandler.create(corsOptions.getAllowedOrigin()); if (corsOptions.getAllowedHeaders() != null) { corsHandler.allowedHeaders(corsOptions.getAllowedHeaders()); } corsHandler.allowCredentials(corsOptions.isAllowCredentials()); if (corsOptions.getExposedHeaders() != null) { corsHandler.exposedHeaders(corsOptions.getExposedHeaders()); } if (corsOptions.getAllowedMethods() != null) { corsHandler.allowedMethods(corsOptions.getAllowedMethods()); } corsHandler.maxAgeSeconds(corsOptions.getMaxAgeSeconds()); httpsRouter.route().handler(corsHandler); } // 创建https服务器 serverOptions.setSsl(true); VxApiCertOptions certOptions = serverOptions.getCertOptions(); if (certOptions.getCertType().equalsIgnoreCase("pem")) { serverOptions .setPemKeyCertOptions(new PemKeyCertOptions().setCertPath(certOptions.getCertPath()).setKeyPath(certOptions.getCertKey())); } else if (certOptions.getCertType().equalsIgnoreCase("pfx")) { serverOptions.setPfxKeyCertOptions(new PfxOptions().setPath(certOptions.getCertPath()).setPassword(certOptions.getCertKey())); } else { LOG.error("创建https服务器-->失败:无效的证书类型,只支持pem/pfx格式的证书"); createHttps.handle(Future.failedFuture("创建https服务器-->失败:无效的证书类型,只支持pem/pfx格式的证书")); return; } Future<Boolean> createFuture = Future.future(); vertx.fileSystem().exists(certOptions.getCertPath(), createFuture); createFuture.setHandler(check -> { if (check.succeeded()) { if (check.result()) { // 404页面 httpsRouter.route().order(999999).handler(rct -> { if (LOG.isDebugEnabled()) { LOG.debug( "用户: " + rct.request().remoteAddress().host() + "请求的了不存的路径: " + rct.request().method() + ":" + rct.request().path()); } HttpServerResponse response = rct.response(); if (appOption.getNotFoundContentType() != null) { response.putHeader("Content-Type", appOption.getNotFoundContentType()); } response.end(appOption.getNotFoundResult()); }); // 如果在linux系统开启epoll if (vertx.isNativeTransportEnabled()) { serverOptions.setTcpFastOpen(true).setTcpCork(true).setTcpQuickAck(true).setReusePort(true); } vertx.createHttpServer(serverOptions).requestHandler(httpsRouter::accept).listen(serverOptions.getHttpsPort(), res -> { if (res.succeeded()) { System.out.println(appOption.getAppName() + " Running on port " + serverOptions.getHttpsPort() + " by HTTPS"); createHttps.handle(Future.succeededFuture()); } else { System.out.println("create HTTPS Server failed : " + res.cause()); createHttps.handle(Future.failedFuture(res.cause())); } }); } else { LOG.error("执行创建https服务器-->失败:无效的证书或者错误的路径:如果证书存放在conf/cert中,路径可以从cert/开始,示例:cert/XXX.XXX"); createHttps.handle(Future.failedFuture("无效的证书或者错误的路径")); } } else { LOG.error("执行创建https服务器-->失败:无效的证书或者错误的路径:如果证书存放在conf/cert中,路径可以从cert/开始,示例:cert/XXX.XXX", check.cause()); createHttps.handle(Future.failedFuture(check.cause())); } }); }
Example #30
Source File: VxApiApplication.java From VX-API-Gateway with MIT License | 4 votes |
/** * 创建http服务器 * * @param createHttp */ public void createHttpServer(Handler<AsyncResult<Void>> createHttp) { this.httpRouter = Router.router(vertx); httpRouter.route().handler(this::filterBlackIP); httpRouter.route().handler(CookieHandler.create()); SessionStore sessionStore = null; if (vertx.isClustered()) { sessionStore = ClusteredSessionStore.create(vertx); } else { sessionStore = LocalSessionStore.create(vertx); } SessionHandler sessionHandler = SessionHandler.create(sessionStore); sessionHandler.setSessionCookieName(appOption.getSessionCookieName()); sessionHandler.setSessionTimeout(appOption.getSessionTimeOut()); httpRouter.route().handler(sessionHandler); // 跨域处理 if (corsOptions != null) { CorsHandler corsHandler = CorsHandler.create(corsOptions.getAllowedOrigin()); if (corsOptions.getAllowedHeaders() != null) { corsHandler.allowedHeaders(corsOptions.getAllowedHeaders()); } corsHandler.allowCredentials(corsOptions.isAllowCredentials()); if (corsOptions.getExposedHeaders() != null) { corsHandler.exposedHeaders(corsOptions.getExposedHeaders()); } if (corsOptions.getAllowedMethods() != null) { corsHandler.allowedMethods(corsOptions.getAllowedMethods()); } corsHandler.maxAgeSeconds(corsOptions.getMaxAgeSeconds()); httpRouter.route().handler(corsHandler); } // 如果在linux系统开启epoll if (vertx.isNativeTransportEnabled()) { serverOptions.setTcpFastOpen(true).setTcpCork(true).setTcpQuickAck(true).setReusePort(true); } // 404页面 httpRouter.route().order(999999).handler(rct -> { if (LOG.isDebugEnabled()) { LOG.debug("用户: " + rct.request().remoteAddress().host() + "请求的了不存的路径: " + rct.request().method() + ":" + rct.request().path()); } HttpServerResponse response = rct.response(); if (appOption.getNotFoundContentType() != null) { response.putHeader("Content-Type", appOption.getNotFoundContentType()); } response.end(appOption.getNotFoundResult()); }); // 创建http服务器 vertx.createHttpServer(serverOptions).requestHandler(httpRouter::accept).listen(serverOptions.getHttpPort(), res -> { if (res.succeeded()) { System.out.println( MessageFormat.format("{0} Running on port {1} by HTTP", appOption.getAppName(), Integer.toString(serverOptions.getHttpPort()))); createHttp.handle(Future.succeededFuture()); } else { System.out.println("create HTTP Server failed : " + res.cause()); createHttp.handle(Future.failedFuture(res.cause())); } }); }