List of usage examples for io.vertx.core.json JsonObject getString
public String getString(String key)
From source file:io.knotx.server.KnotxServerConfiguration.java
License:Apache License
private RoutingEntry parseRoutingCriteria(JsonObject object) { return new RoutingEntry(object.getString("path"), object.getString("address"), parseOnTransition(object.getJsonObject("onTransition"))); }
From source file:io.knotx.splitter.FragmentSplitterConfiguration.java
License:Apache License
public FragmentSplitterConfiguration(JsonObject config) { address = config.getString("address"); }
From source file:io.nitor.api.backend.auth.SetupAzureAdConnectAuth.java
License:Apache License
private static Handler<RoutingContext> authHandler(JsonObject adAuth, Set<String> forbiddenHeaders, HashMap<String, Pattern> requiredHeaderMatchers, String publicURI, boolean virtualHosting, CookieSessionHandler sessionHandler, String redirectUri, RedirectTokenService redirectTokenService) { String publicHost = getUriHostName(publicURI); return ctx -> { Optional<Map<String, String>> headers = ofNullable(sessionHandler.getSessionData(ctx)); if (headers.isPresent()) { MultiMap h = ctx.request().headers(); forbiddenHeaders.forEach(h::remove); headers.get().entrySet().stream().filter(e -> !e.getKey().startsWith(SECRET_DATA_PREFIX)) .forEach(e -> h.set(e.getKey(), e.getValue())); if (!requiredHeaderMatchers.entrySet().stream() .allMatch(e -> headerMatches(h.get(e.getKey()), e.getValue()))) { logger.info("Not authorised to view resource '" + ctx.request().path() + "' with session data: " + headers.get()); ctx.reroute(GET, FORBIDDEN_PATH); return; }/* ww w .j ava 2 s . co m*/ ctx.next(); return; } String publicURIWithoutProtocol = getUriHostName(publicURI); String host = getUriHostName(ctx.request().host()); if (virtualHosting && !publicURIWithoutProtocol.equals(host)) { // phase 1: executed iff authentication cookie is missing && the browser is not on the auth domain but on a virtual domain // -> jump to auth domain and pass the current url inside token String currentUri = forceHttps(replaceHostAndPort(ctx.request().absoluteURI(), host)); String token = redirectTokenService.createToken(ctx, singletonMap("u", currentUri)); ctx.response() .setStatusCode((ctx.request().method() == GET ? TEMPORARY_REDIRECT : SEE_OTHER).code()) // ask browser to turn POST etc into GET when redirecting .putHeader(CACHE_CONTROL, "no-cache, no-store, must-revalidate").putHeader(EXPIRES, "0") .putHeader(LOCATION, publicURI + PROXY_AUTH_REDIRECT_BEFORE + "?t=" + urlEncode(token)) .end(); return; } StringBuilder sb = new StringBuilder(); String currentUri = forceHttps(replaceHost(ctx.request().absoluteURI(), publicHost)); sb.append(adAuth.getJsonObject("openIdConfig").getString("authorization_endpoint")) .append("?domain_hint=organizations&response_type=code&response_mode=query") .append("&client_id=").append(urlEncode(adAuth.getString("clientId"))).append("&redirect_uri=") .append(urlEncode(redirectUri)).append("&scope=").append(urlEncode(adAuth.getString("scope"))) //.append("&login_hint=").append(urlEncode(previousKnownUserName)) -- could try to fetch it from expired session cookie? //.append("&prompt=").append("login") -- force login - maybe do if IP is from different country? .append("&state=") .append(urlEncode(redirectTokenService.createToken(ctx, singletonMap("a", currentUri)))); ctx.response().setStatusCode(TEMPORARY_REDIRECT.code()).putHeader(LOCATION, sb) .putHeader(CACHE_CONTROL, "no-cache, no-store, must-revalidate").putHeader(EXPIRES, "0").end(); }; }
From source file:io.nitor.api.backend.auth.SetupAzureAdConnectAuth.java
License:Apache License
private static void finalizeAuthentication(RoutingContext ctx, JsonObject adAuth, HttpClient httpClient, CookieSessionHandler sessionHandler, List<GraphQuery> graphQueries, String redirectUri, RedirectTokenService redirectTokenService) { Map<String, String> params = redirectTokenService.getParameters(ctx, ctx.request().getParam("state")); if (params == null || params.get("a") == null) { logger.error("Missing state parameter"); ctx.reroute(GET, UNAUTHORIZED_PATH); return;/* w ww . ja v a 2s . com*/ } String originalUrl = params.get("a"); String code = ctx.request().getParam("code"); String graphScopes = adAuth.getString("scope"); Buffer form = Buffer .buffer("code=" + urlEncode(code) + "&client_id=" + urlEncode(adAuth.getString("clientId")) + "&scope=" + urlEncode(graphScopes) + "&grant_type=authorization_code" + "&client_secret=" + urlEncode(adAuth.getString("clientSecret")) + "&redirect_uri=" + urlEncode(redirectUri)); String tokenUrl = adAuth.getJsonObject("openIdConfig").getString("token_endpoint"); logger.debug("Requesting graph access token from " + tokenUrl + " with [ " + form + "]"); httpClient.postAbs(tokenUrl).putHeader(ACCEPT, APPLICATION_JSON) .putHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .putHeader(CONTENT_LENGTH, String.valueOf(form.length())).setTimeout(SECONDS.toMillis(10)) .exceptionHandler(err -> { logger.error("Failed to fetch graph access token", err); ctx.reroute(GET, UNAUTHORIZED_PATH); }).handler(resp -> processGraphTokenResponse(resp, ctx, httpClient, sessionHandler, graphQueries, originalUrl)) .end(form); }
From source file:io.nitor.api.backend.auth.SetupAzureAdConnectAuth.java
License:Apache License
static void processGraphTokenResponse(HttpClientResponse resp, RoutingContext ctx, HttpClient httpClient, CookieSessionHandler sessionHandler, List<GraphQuery> graphQueries, String originalUrl) { if (resp.statusCode() != OK.code()) { resp.bodyHandler(body -> {/*w w w . ja v a2 s .c om*/ logger.warn("Failed to fetch graph access token: " + resp.statusMessage() + " - " + resp.getHeader(WWW_AUTHENTICATE) + " ::: " + body); ctx.reroute(GET, UNAUTHORIZED_PATH); }); return; } resp.bodyHandler(body -> { JsonObject json = body.toJsonObject(); String token = json.getString("access_token"); String refreshToken = json.getString("refresh_token"); // clean out sensitive stuff json.put("access_token", "<censored>"); json.put("refresh_token", "<censored>"); logger.debug("Got graph access response: {}", json); final AtomicInteger pendingRequests = new AtomicInteger(graphQueries.size()); final Map<String, String> sessionData = new HashMap<>(); ofNullable(refreshToken).ifPresent(t -> sessionData.put(GRAPH_ACCESS_TOKEN_KEY, t)); for (GraphQuery query : graphQueries) { String clientRequestId = UUID.randomUUID().toString(); logger.debug("Requesting " + query.graphQueryURI + "[" + clientRequestId + "]"); httpClient.getAbs(query.graphQueryURI).putHeader(AUTHORIZATION, "Bearer " + token) .putHeader(ACCEPT, APPLICATION_JSON).putHeader("client-request-id", clientRequestId) .setTimeout(SECONDS.toMillis(10)).exceptionHandler(err -> { if (pendingRequests.getAndSet(-1) != -1) { logger.error("Failed to fetch user information [" + clientRequestId + "]", err); ctx.reroute(GET, UNAUTHORIZED_PATH); } }).handler(r -> processMicrosoftUserInformation(r, ctx, sessionHandler, query.headerMappings, originalUrl, pendingRequests, sessionData, clientRequestId)) .end(); } }); }
From source file:io.nitor.api.backend.auth.SimpleConfigAuthProvider.java
License:Apache License
@Override public void authenticate(JsonObject authInfo, Handler<AsyncResult<User>> resultHandler) { AsyncResult<User> result;/*from w w w . j av a 2s. c om*/ String username = authInfo.getString("username"); if (users.getOrDefault(username, "").equals(authInfo.getString("password"))) { result = new SucceededResult<>(new SimpleUser(username)); } else { result = new FailedResult<>(new RuntimeException("Auth failed")); } resultHandler.handle(result); }
From source file:io.nitor.api.backend.lambda.LambdaHandler.java
License:Apache License
public LambdaHandler(JsonObject conf, int routeLength) { this.routeLength = routeLength; Region region = resolveRegion(conf); lambdaCl = LambdaAsyncClient.builder().region(region).credentialsProvider(resolveCredentialsProvider(conf)) .build();/*from w w w . ja va 2 s . com*/ pathTemplateMatcher = new PathTemplateMatcher<>(); for (Object next : conf.getJsonArray("paths")) { if (next instanceof JsonObject) { JsonObject nextObj = (JsonObject) next; String lambdaFunction = nextObj.getString("function"); String qualifier = conf.getString("qualifier", "$LATEST"); Entry<String, String> value = new SimpleImmutableEntry<>(lambdaFunction, qualifier); pathTemplateMatcher.add(PathTemplate.create(nextObj.getString("template")), value); } } }
From source file:io.nitor.api.backend.lambda.LambdaHandler.java
License:Apache License
@Override public void handle(RoutingContext ctx) { HttpServerRequest sreq = ctx.request(); final String path = normalizePath(sreq.path(), routeLength); if (path == null) { ctx.response().setStatusCode(NOT_FOUND.code()).end(); return;/* w w w. jav a 2 s.c om*/ } HttpServerResponse sres = ctx.response(); PathMatchResult<Entry<String, String>> matchRes = pathTemplateMatcher.match(path); final String lambdaFunction, qualifier; if (matchRes == null) { logger.error("No matching path template"); sres.setStatusCode(BAD_GATEWAY.code()); return; } else { lambdaFunction = matchRes.getValue().getKey(); qualifier = matchRes.getValue().getValue(); } sreq.bodyHandler(new Handler<Buffer>() { @Override public void handle(Buffer event) { byte[] body = event.getBytes(); APIGatewayProxyRequestEvent reqObj = new APIGatewayProxyRequestEvent(); /* * Handle body */ String bodyObjStr = null; boolean isBase64Encoded = true; if (body != null && body.length > 0) { String ct = sreq.getHeader("content-type").toLowerCase(); if (ct.startsWith("text/") || ct.startsWith("application/json") || (ct.indexOf("charset=") > 0)) { String charset = "utf-8"; if (ct.indexOf("charset=") > 0) { charset = getCharsetFromContentType(ct); } try { bodyObjStr = Charset.forName(charset).newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(body)) .toString(); isBase64Encoded = false; } catch (CharacterCodingException e) { logger.error("Decoding body failed", e); } } if (bodyObjStr == null) { bodyObjStr = Base64.getEncoder().encodeToString(body); } reqObj = reqObj.withBody(bodyObjStr).withIsBase64Encoded(isBase64Encoded); } Map<String, List<String>> headerMultivalue = sreq.headers().entries().stream() .collect(toMap(Entry::getKey, x -> sreq.headers().getAll(x.getKey()))); Map<String, String> headerValue = sreq.headers().entries().stream() .collect(toMap(Entry::getKey, Entry::getValue)); /* * Handle request context */ RequestIdentity reqId = new RequestIdentity().withSourceIp(getRemoteAddress(ctx)) .withUserAgent(sreq.getHeader(USER_AGENT)); if (ctx.user() != null) { reqId.withUser(ctx.user().principal().toString()); } ProxyRequestContext reqCtx = new ProxyRequestContext() .withPath(sreq.path().substring(0, routeLength)).withHttpMethod(sreq.method().toString()) .withIdentity(reqId); reqObj = reqObj.withMultiValueHeaders(headerMultivalue).withHeaders(headerValue) .withHttpMethod(sreq.method().toString()).withPath(sreq.path()).withResource(path) .withQueryStringParameters(splitQuery(sreq.query())) .withMultiValueQueryStringParameters(splitMultiValueQuery(sreq.query())) .withPathParameters(matchRes.getParameters()).withRequestContext(reqCtx); String reqStr = JsonObject.mapFrom(reqObj).toString(); byte[] sendBody = reqStr.getBytes(UTF_8); InvokeRequest req = InvokeRequest.builder().invocationType(InvocationType.REQUEST_RESPONSE) .functionName(lambdaFunction).qualifier(qualifier).payload(SdkBytes.fromByteArray(sendBody)) .build(); logger.info("Calling lambda " + lambdaFunction + ":" + qualifier); logger.debug("Payload: " + reqStr); CompletableFuture<InvokeResponse> respFuture = lambdaCl.invoke(req); respFuture.whenComplete((iresp, err) -> { if (iresp != null) { try { String payload = iresp.payload().asString(UTF_8); JsonObject resp = new JsonObject(payload); int statusCode = resp.getInteger("statusCode"); sres.setStatusCode(statusCode); for (Entry<String, Object> next : resp.getJsonObject("headers").getMap().entrySet()) { sres.putHeader(next.getKey(), next.getValue().toString()); } String respBody = resp.getString("body"); byte[] bodyArr = new byte[0]; if (body != null && !respBody.isEmpty()) { if (TRUE.equals(resp.getBoolean("isBase64Encoded"))) { bodyArr = Base64.getDecoder().decode(body); } else { bodyArr = respBody.getBytes(UTF_8); } } sres.putHeader(CONTENT_LENGTH, String.valueOf(bodyArr.length)); Buffer buffer = Buffer.buffer(bodyArr); tryToCacheContent(ctx, buffer); sres.write(buffer); } catch (Throwable t) { logger.error("Error processing lambda request", t); if (!sres.headWritten()) { sres.setStatusCode(BAD_GATEWAY.code()); sres.putHeader(CONTENT_TYPE, "application/json"); Buffer response = Buffer.buffer(new LambdaErrorResponse(t).toString()); sres.putHeader(CONTENT_LENGTH, String.valueOf(response.length())); sres.write(response); } } finally { sres.end(); } } else { logger.error("Error processing lambda request", err); sres.setStatusCode(BAD_GATEWAY.code()); sres.putHeader(CONTENT_TYPE, "application/json"); Buffer response = Buffer.buffer(new LambdaErrorResponse(err).toString()); sres.putHeader(CONTENT_LENGTH, String.valueOf(response.length())); sres.end(response); } }); } }); }
From source file:io.nitor.api.backend.msgraph.GraphSessionTokenService.java
License:Apache License
public GraphSessionTokenService(HttpClient httpClient, JsonObject adConfig) { this.tokenUrl = adConfig.getJsonObject("openIdConfig").getString("token_endpoint"); this.baseForm = "client_id=" + urlEncode(adConfig.getString("clientId")) + "&scope=" + urlEncode(adConfig.getString("scope")) + "&grant_type=refresh_token" + "&client_secret=" + urlEncode(adConfig.getString("clientSecret")) + "&redirect_uri=" + urlEncode(adConfig.getString("redirectUri")); this.httpClient = httpClient; }
From source file:io.nitor.api.backend.msgraph.GraphSessionTokenService.java
License:Apache License
private void handleRefreshResponse(HttpClientResponse resp, Future<TokenData> future, String previousRefreshToken) { resp.exceptionHandler(future::fail); resp.bodyHandler(body -> {/*ww w. j a va2 s.c o m*/ if (resp.statusCode() != 200) { future.fail(body.toString()); return; } JsonObject json = body.toJsonObject(); TokenData d = new TokenData(json.getString("access_token"), currentTimeMillis() + 1_000 * (json.getLong("expires_in") - 10), json.getString("refresh_token")); cache.put(d.refreshToken, d); if (previousRefreshToken != null) { cache.put(previousRefreshToken, d); } future.complete(d); }); }