List of usage examples for io.vertx.core.http HttpHeaders AUTHORIZATION
CharSequence AUTHORIZATION
To view the source code for io.vertx.core.http HttpHeaders AUTHORIZATION.
Click Source Link
From source file:com.hubrick.vertx.rest.impl.DefaultRestClientRequest.java
License:Apache License
@Override public void setBasicAuth(String userPassCombination) { bufferedHttpOutputMessage.getHeaders().set(HttpHeaders.AUTHORIZATION, "Basic " + BaseEncoding.base64().encode(userPassCombination.getBytes(Charsets.UTF_8))); }
From source file:com.hubrick.vertx.rest.impl.DefaultRestClientRequest.java
License:Apache License
@Override public String getBasicAuth() { final String base64UserPassCombination = bufferedHttpOutputMessage.getHeaders() .get(HttpHeaders.AUTHORIZATION); if (base64UserPassCombination != null && base64UserPassCombination.startsWith("Basic")) { return new String(BaseEncoding.base64().decode(base64UserPassCombination), Charsets.UTF_8) .replaceFirst("Basic", "").trim(); } else {/* w ww . ja v a 2s . co m*/ return null; } }
From source file:de.elsibay.EbbTicketShowcase.java
License:Open Source License
@Override public void start(Future<Void> startFuture) throws Exception { SessionStore sessionStore = LocalSessionStore.create(vertx); Router backendRouter = Router.router(vertx); backendRouter.route().handler(LoggerHandler.create(LoggerHandler.DEFAULT_FORMAT)); CookieHandler cookieHandler = CookieHandler.create(); SessionHandler sessionHandler = SessionHandler.create(sessionStore); // the CORS OPTION request must not set cookies backendRouter.get().handler(cookieHandler); backendRouter.get().handler(sessionHandler); backendRouter.post().handler(cookieHandler); backendRouter.post().handler(sessionHandler); // setup CORS CorsHandler corsHandler = CorsHandler.create("http(s)?://" + WEBSERVER_HOST + ":" + WEBSERVER_PORT) .allowCredentials(true).allowedHeader(HttpHeaders.ACCEPT.toString()) .allowedHeader(HttpHeaders.ORIGIN.toString()).allowedHeader(HttpHeaders.AUTHORIZATION.toString()) .allowedHeader(HttpHeaders.CONTENT_TYPE.toString()).allowedHeader(HttpHeaders.COOKIE.toString()) .exposedHeader(HttpHeaders.SET_COOKIE.toString()).allowedMethod(HttpMethod.POST) .allowedMethod(HttpMethod.PUT).allowedMethod(HttpMethod.GET).allowedMethod(HttpMethod.DELETE); // setup event bus bridge TicketEventbusBridge sebb = new TicketEventbusBridge(sessionStore); backendRouter.mountSubRouter("/eventbus", sebb.route(vertx)); // dummy eventbus services vertx.eventBus().consumer("ping", (Message<JsonObject> msg) -> { msg.reply(new JsonObject().put("answer", "pong " + msg.body().getString("text", ""))); });// ww w.jav a 2 s . c om vertx.setPeriodic(5000, id -> { vertx.eventBus().send("topic", new JsonObject().put("timestamp", new Date().getTime())); }); // session manager for login backendRouter.route("/api/*").handler(corsHandler); backendRouter.route("/api/*").method(HttpMethod.POST).method(HttpMethod.PUT).handler(BodyHandler.create()); backendRouter.route("/api/session").handler((RoutingContext rc) -> { JsonObject user = rc.getBodyAsJson(); String sessionId = rc.session().id(); rc.session().put("user", user); rc.response().end(user.copy().put("sessionId", sessionId).encodePrettily()); }); // dummy ping REST service backendRouter.route("/api/ping").handler((RoutingContext rc) -> { JsonObject replyMsg = new JsonObject(); replyMsg.put("timestamp", new Date().getTime()); Cookie sessionCookie = rc.getCookie(SessionHandler.DEFAULT_SESSION_COOKIE_NAME); if (sessionCookie != null) { replyMsg.put("sessionId", sessionCookie.getValue()); } rc.response().end(replyMsg.encode()); }); // start backend on one port vertx.createHttpServer().requestHandler(backendRouter::accept).listen(BACKENDSERVER_PORT, BACKENDSERVER_HOST, (AsyncResult<HttpServer> async) -> { System.out .println(async.succeeded() ? "Backend Server started" : "Backend Server start FAILED"); }); // static files on other port Router staticFilesRouter = Router.router(vertx); staticFilesRouter.route("/*").handler(StaticHandler.create("src/main/www").setCachingEnabled(false)); vertx.createHttpServer().requestHandler(staticFilesRouter::accept).listen(WEBSERVER_PORT, WEBSERVER_HOST, (AsyncResult<HttpServer> async) -> { System.out.println(async.succeeded() ? "Web Server started\ngoto http://" + WEBSERVER_HOST + ":" + WEBSERVER_PORT + "/" : "Web Server start FAILED"); }); }
From source file:examples.GraphQLExamples.java
License:Apache License
public void handlerSetupGraphiQLAuthn(GraphQL graphQL, Router router) { GraphQLHandlerOptions options = new GraphQLHandlerOptions() .setGraphiQLOptions(new GraphiQLOptions().setEnabled(true)); GraphQLHandler graphQLHandler = GraphQLHandler.create(graphQL, options).graphiQLRequestHeaders(rc -> { String token = rc.get("token"); return MultiMap.caseInsensitiveMultiMap().add(HttpHeaders.AUTHORIZATION, "Bearer " + token); });/*w w w . j a v a 2 s . c o m*/ }
From source file:io.github.cdelmas.spike.vertx.infrastructure.auth.BearerAuthHandler.java
License:Apache License
@Override public void handle(RoutingContext routingContext) { HttpServerRequest request = routingContext.request(); request.pause();/*w ww .ja v a2 s . c om*/ String authorization = request.headers().get(HttpHeaders.AUTHORIZATION); if (authorization == null) { routingContext.fail(401); } else { String[] parts = authorization.split(" "); if (parts.length != 2) { routingContext.fail(401); } else { String scheme = parts[0]; if (!"bearer".equalsIgnoreCase(scheme)) { routingContext.fail(401); } else { String token = parts[1]; JsonObject credentials = new JsonObject(); credentials.put("token", token); authProvider.authenticate(credentials, res -> { if (res.succeeded()) { routingContext.setUser(res.result()); request.resume(); routingContext.next(); } else { routingContext.fail(401); } }); } } } }
From source file:org.eclipse.hono.adapter.http.HonoAuthHandlerImpl.java
License:Open Source License
protected final void parseAuthorization(RoutingContext ctx, boolean optional, Handler<AsyncResult<String>> handler) { final HttpServerRequest request = ctx.request(); final String authorization = request.headers().get(HttpHeaders.AUTHORIZATION); if (authorization == null) { if (optional) { // this is allowed handler.handle(Future.succeededFuture()); } else {//w ww .j a v a 2 s.c o m handler.handle(Future.failedFuture(UNAUTHORIZED)); } return; } try { int idx = authorization.indexOf(' '); if (idx <= 0) { handler.handle(Future.failedFuture(BAD_REQUEST)); return; } if (!type.is(authorization.substring(0, idx))) { handler.handle(Future.failedFuture(UNAUTHORIZED)); return; } handler.handle(Future.succeededFuture(authorization.substring(idx + 1))); } catch (RuntimeException e) { handler.handle(Future.failedFuture(e)); } }
From source file:org.eclipse.hono.adapter.http.HonoBasicAuthHandler.java
License:Open Source License
/** * Extracts authentication information from the <em>Authorization</em> * header of an HTTP request./*from w ww . ja va 2s.co m*/ * * @param ctx The routing context that contains the HTTP request. * @param optional Indicates whether the authorization header is mandatory. * @param handler The handler to invoke with the authentication info. */ protected final void parseAuthorization(final RoutingContext ctx, final boolean optional, final Handler<AsyncResult<String>> handler) { final HttpServerRequest request = ctx.request(); final String authorization = request.headers().get(HttpHeaders.AUTHORIZATION); if (authorization == null) { if (optional) { // this is allowed handler.handle(Future.succeededFuture()); } else { handler.handle(Future.failedFuture(UNAUTHORIZED)); } return; } try { final int idx = authorization.indexOf(' '); if (idx <= 0) { handler.handle(Future.failedFuture(BAD_REQUEST)); return; } if (!"Basic".equalsIgnoreCase(authorization.substring(0, idx))) { handler.handle(Future.failedFuture(UNAUTHORIZED)); return; } handler.handle(Future.succeededFuture(authorization.substring(idx + 1))); } catch (RuntimeException e) { handler.handle(Future.failedFuture(e)); } }
From source file:org.eclipse.hono.adapter.http.vertx.VertxBasedHttpProtocolAdapter.java
License:Open Source License
private void addTelemetryApiRoutes(final Router router, final Handler<RoutingContext> authHandler) { // support CORS headers for PUTing telemetry router.routeWithRegex("\\/telemetry\\/[^\\/]+\\/.*") .handler(CorsHandler.create(getConfig().getCorsAllowedOrigin()).allowedMethod(HttpMethod.PUT) .allowedHeader(HttpHeaders.AUTHORIZATION.toString()) .allowedHeader(HttpHeaders.CONTENT_TYPE.toString())); if (getConfig().isAuthenticationRequired()) { // support CORS headers for POSTing telemetry router.route("/telemetry") .handler(CorsHandler.create(getConfig().getCorsAllowedOrigin()).allowedMethod(HttpMethod.POST) .allowedHeader(HttpHeaders.AUTHORIZATION.toString()) .allowedHeader(HttpHeaders.CONTENT_TYPE.toString())); // require auth for POSTing telemetry router.route(HttpMethod.POST, "/telemetry").handler(authHandler); // route for posting telemetry data using tenant and device ID determined as part of // device authentication router.route(HttpMethod.POST, "/telemetry").handler(this::handlePostTelemetry); // require auth for PUTing telemetry router.route(HttpMethod.PUT, "/telemetry/*").handler(authHandler); // assert that authenticated device's tenant matches tenant from path variables router.route(HttpMethod.PUT, String.format("/telemetry/:%s/:%s", PARAM_TENANT, PARAM_DEVICE_ID)) .handler(this::assertTenant); }/*from w w w . ja v a 2 s. c o m*/ // route for uploading telemetry data router.route(HttpMethod.PUT, String.format("/telemetry/:%s/:%s", PARAM_TENANT, PARAM_DEVICE_ID)) .handler(ctx -> uploadTelemetryMessage(ctx, getTenantParam(ctx), getDeviceIdParam(ctx))); }
From source file:org.eclipse.hono.adapter.http.vertx.VertxBasedHttpProtocolAdapter.java
License:Open Source License
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(HttpHeaders.AUTHORIZATION.toString()) .allowedHeader(HttpHeaders.CONTENT_TYPE.toString())); if (getConfig().isAuthenticationRequired()) { // support CORS headers for POSTing events router.route("/event") .handler(CorsHandler.create(getConfig().getCorsAllowedOrigin()).allowedMethod(HttpMethod.POST) .allowedHeader(HttpHeaders.AUTHORIZATION.toString()) .allowedHeader(HttpHeaders.CONTENT_TYPE.toString())); // require auth for POSTing events router.route(HttpMethod.POST, "/event").handler(authHandler); // route for posting events using tenant and device ID determined as part of // device authentication router.route(HttpMethod.POST, "/event").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); }/*from w w w.j av a 2s .com*/ // 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))); }
From source file:org.eclipse.hono.devices.HonoHttpDevice.java
License:Open Source License
/** * Send a message to Hono HTTP adapter. Delay any successful response by 1000 milliseconds. * * @param payload JSON object that will be sent as UTF-8 encoded String. * @param headersToAdd A map that contains all headers to add to the http request. * @param asEvent If {@code true}, an event message is sent, otherwise a telemetry message. * @return CompletableFuture<MultiMap> A completable future that contains the HTTP response in a MultiMap. */// www.java 2 s . c o m private CompletableFuture<MultiMap> sendMessage(final JsonObject payload, final MultiMap headersToAdd, final boolean asEvent) { final CompletableFuture<MultiMap> result = new CompletableFuture<>(); final Predicate<Integer> successfulStatus = statusCode -> statusCode == HttpURLConnection.HTTP_ACCEPTED; final HttpClientRequest req = vertx.createHttpClient() .post(HONO_HTTP_ADAPTER_PORT, HONO_HTTP_ADAPTER_HOST, asEvent ? "/event" : "/telemetry") .handler(response -> { if (successfulStatus.test(response.statusCode())) { vertx.setTimer(1000, l -> result.complete(response.headers())); } else { result.completeExceptionally(new ServiceInvocationException(response.statusCode())); } }).exceptionHandler(t -> result.completeExceptionally(t)); req.headers().addAll(headersToAdd); req.headers() .addAll(MultiMap.caseInsensitiveMultiMap() .add(HttpHeaders.AUTHORIZATION, getBasicAuth(TENANT_ID, DEVICE_AUTH_ID, DEVICE_PASSWORD)) .add(HttpHeaders.ORIGIN, ORIGIN_URI)); if (payload == null) { req.end(); } else { req.end(payload.encode()); } return result; }