io.vertx.reactivex.ext.web.RoutingContext Java Examples

The following examples show how to use io.vertx.reactivex.ext.web.RoutingContext. 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: IntrospectionEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private static IntrospectionRequest createRequest(RoutingContext context) {
    String token = context.request().getParam(TOKEN_PARAM);
    String tokenTypeHint = context.request().getParam(TOKEN_TYPE_HINT_PARAM);

    if (token == null) {
        throw new InvalidRequestException();
    }

    IntrospectionRequest introspectionRequest = new IntrospectionRequest(token);

    if (tokenTypeHint != null) {
        try {
            introspectionRequest.setHint(TokenTypeHint.from(tokenTypeHint));
        } catch (IllegalArgumentException iae) {
            throw new UnsupportedTokenType(tokenTypeHint);
        }
    }

    return introspectionRequest;
}
 
Example #2
Source File: ActionHelper.java    From introduction-to-eclipse-vertx with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a bi-consumer writing the received {@link AsyncResult} to the routing context and setting
 * the HTTP status to the given status.
 *
 * @param context the routing context
 * @param status  the status
 * @return the bi-consumer
 */
private static <T> BiConsumer<T, Throwable> writeJsonResponse(RoutingContext context, int status) {
    return (res, err) -> {
        if (err != null) {
            if (err instanceof NoSuchElementException) {
                context.response().setStatusCode(404).end(err.getMessage());
            } else {
                context.fail(err);
            }
        } else {
            context.response().setStatusCode(status)
                .putHeader("content-type", "application/json; charset=utf-8")
                .end(Json.encodePrettily(res));
        }
    };
}
 
Example #3
Source File: DynamicClientAccessTokenHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    final JWT token = context.get(OAuth2AuthHandler.TOKEN_CONTEXT_KEY);
    final Client client = context.get(OAuth2AuthHandler.CLIENT_CONTEXT_KEY);

    if (token.hasScope(Scope.DCR_ADMIN.getKey())) {
        context.next();
        return;
    }

    // if not dcr admin, access token must match client registration token
    final String rawToken = context.get(OAuth2AuthHandler.RAW_TOKEN_CONTEXT_KEY);
    if (rawToken == null || !rawToken.equals(client.getRegistrationAccessToken())) {
        context.fail(new ClientRegistrationForbiddenException("Non matching registration_access_token"));
        return;
    }

    // registration token sub must match the client_id parameter
    final String clientIdPathParameter = context.request().getParam(Parameters.CLIENT_ID);
    if (!isRequestPathClientIdMatching(token, clientIdPathParameter)) {
        context.fail(new ClientRegistrationForbiddenException("Not allowed to access to : " + clientIdPathParameter));
        return;
    }

    context.next();
}
 
Example #4
Source File: IntrospectionEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    // If the protected resource uses OAuth 2.0 client credentials to
    // authenticate to the introspection endpoint and its credentials are
    // invalid, the authorization server responds with an HTTP 401
    Client client = context.get(CONTEXT_CLIENT_KEY);
    if (client == null) {
        throw new InvalidClientException();
    }

    introspectionService
            .introspect(createRequest(context))
            .doOnSuccess(introspectionResponse -> context.response()
                    .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                    .putHeader(HttpHeaders.PRAGMA, "no-cache")
                    .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                    .end(Json.encodePrettily(introspectionResponse)))
            .subscribe();
}
 
Example #5
Source File: ResourceAccessPoliciesEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
public void get(RoutingContext context) {
    final JWT accessToken = context.get(OAuth2AuthHandler.TOKEN_CONTEXT_KEY);
    final Client client = context.get(OAuth2AuthHandler.CLIENT_CONTEXT_KEY);
    final String resource = context.request().getParam(RESOURCE_ID);
    final String accessPolicyId = context.request().getParam(POLICY_ID);

    resourceService.findAccessPolicy(domain.getId(), client.getId(), accessToken.getSub(), resource, accessPolicyId)
            .switchIfEmpty(Single.error(new AccessPolicyNotFoundException(accessPolicyId)))
            .subscribe(
                    response -> context.response()
                            .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                            .putHeader(HttpHeaders.PRAGMA, "no-cache")
                            .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                            .end(Json.encodePrettily(response))
                    , error -> context.fail(error)
            );
}
 
Example #6
Source File: TestResource.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@Path("inject")
@GET
public String inject(@Context Vertx vertx,
		@Context RoutingContext routingContext,
		@Context HttpServerRequest request,
		@Context HttpServerResponse response,
		@Context AuthProvider authProvider,
		@Context User user,
		@Context Session session) {
	if(vertx == null
			|| routingContext == null
			|| request == null
			|| response == null
			|| session == null)
		throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
	return "ok";
}
 
Example #7
Source File: ResourceAccessPoliciesEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
public void delete(RoutingContext context) {
    final JWT accessToken = context.get(OAuth2AuthHandler.TOKEN_CONTEXT_KEY);
    final Client client = context.get(OAuth2AuthHandler.CLIENT_CONTEXT_KEY);
    final String resource = context.request().getParam(RESOURCE_ID);
    final String accessPolicy = context.request().getParam(POLICY_ID);

    resourceService.deleteAccessPolicy(domain.getId(), client.getId(), accessToken.getSub(), resource, accessPolicy)
            .subscribe(
                    () -> context.response()
                            .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                            .putHeader(HttpHeaders.PRAGMA, "no-cache")
                            .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                            .setStatusCode(HttpStatusCode.NO_CONTENT_204)
                            .end()
                    , error -> context.fail(error)
            );
}
 
Example #8
Source File: UserConsentsEndpointHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
/**
 * Revoke consents for a user per application basis or for all applications
 */
public void revoke(RoutingContext context) {
    final String userId = context.request().getParam("userId");
    final String clientId = context.request().getParam("clientId");

    Single.just(Optional.ofNullable(clientId))
            .flatMapCompletable(optClient -> {
                if (optClient.isPresent()) {
                    return getPrincipal(context)
                            .flatMapCompletable(principal -> userService.revokeConsents(userId, optClient.get(), principal));
                }
                return getPrincipal(context)
                        .flatMapCompletable(principal -> userService.revokeConsents(userId, principal));
            })
            .subscribe(
                    () -> context.response().setStatusCode(204).end(),
                    error -> context.fail(error));

}
 
Example #9
Source File: ResourceRegistrationEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
/**
 * https://docs.kantarainitiative.org/uma/wg/rec-oauth-uma-federated-authz-2.0.html#reg-api
 * The spec state that if the resource can not be found, it must result in a 404.
 * By the way this may be better than a 403 to avoid confirming ids to a potential attacks.
 * @param context
 */
public void update(RoutingContext context) {
    JWT accessToken = context.get(OAuth2AuthHandler.TOKEN_CONTEXT_KEY);
    Client client = context.get(OAuth2AuthHandler.CLIENT_CONTEXT_KEY);
    String resource_id = context.request().getParam(RESOURCE_ID);

    this.extractRequest(context)
            .flatMap(request -> this.resourceService.update(request, domain.getId(), client.getId(), accessToken.getSub(), resource_id))
            .subscribe(
                    resource -> context.response()
                            .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                            .putHeader(HttpHeaders.PRAGMA, "no-cache")
                            .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                            .setStatusCode(HttpStatusCode.OK_200)
                            .end(Json.encodePrettily(ResourceResponse.from(resource)))
                    , error -> context.fail(error)
            );
}
 
Example #10
Source File: LoginErrorHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    final HttpServerRequest request = context.request();
    final String error = request.getParam(ERROR_PARAM);
    final String errorCode = request.getParam(ERROR_CODE_PARAM);
    final String errorDescription = request.getParam(ERROR_DESCRIPTION_PARAM);

    // no error to handle, continue
    if (error == null) {
        context.next();
        return;
    }

    // put error data in context
    Map<String, Object> errorContext = new HashMap<>();
    errorContext.put(ERROR_CODE_CONTEXT_KEY, errorCode);
    errorContext.put(ERROR_DESCRIPTION_CONTEXT_KEY, errorDescription);
    context.put(ERROR_CONTEXT_KEY, errorContext);
    context.next();
}
 
Example #11
Source File: ClientRequestParseHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    final String clientId = context.request().getParam(Parameters.CLIENT_ID);
    if (clientId == null || clientId.isEmpty()) {
        if (required) {
            throw new InvalidRequestException("Missing parameter: client_id is required");
        } else {
            context.next();
            return;
        }
    }

    authenticate(clientId, authHandler -> {
        if (authHandler.failed()) {
            context.fail(authHandler.cause());
            return;
        }

        Client safeClient = new Client(authHandler.result());
        safeClient.setClientSecret(null);
        context.put(CLIENT_CONTEXT_KEY, safeClient);
        context.next();
    });
}
 
Example #12
Source File: ErrorEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    final HttpServerRequest request = routingContext.request();
    final String clientId = request.getParam(Parameters.CLIENT_ID);

    if (clientId == null) {
        renderErrorPage(routingContext, null);
        return;
    }

    // fetch client to display its own custom page
    resolveClient(clientId, handler -> {
        if (handler.failed()) {
            // an error occurs while fetching the client
            // we will display the domain error page
            // log this error for the prosperity
            logger.debug("An error occurs while fetching client {}", clientId, handler.cause());
            renderErrorPage(routingContext, null);
            return;
        }

        renderErrorPage(routingContext, handler.result());
    });
}
 
Example #13
Source File: AuthorizationRequestParseRequiredParametersHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    // proceed request parameters
    parseRequestParameters(context);

    // proceed response type parameter
    parseResponseTypeParameter(context);

    // proceed response mode parameter
    parseResponseModeParameter(context);

    // proceed client_id parameter
    parseClientIdParameter(context);

    // proceed nonce parameter
    parseNonceParameter(context);

    context.next();
}
 
Example #14
Source File: ResourceRegistrationEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
public void create(RoutingContext context) {
    JWT accessToken = context.get(OAuth2AuthHandler.TOKEN_CONTEXT_KEY);
    Client client = context.get(OAuth2AuthHandler.CLIENT_CONTEXT_KEY);
    String basePath = UriBuilderRequest.extractBasePath(context);

    this.extractRequest(context)
            .flatMap(request -> this.resourceService.create(request, domain.getId(), client.getId(), accessToken.getSub()))
            .subscribe(
                    resource -> {
                        final String resourceLocation = resourceLocation(basePath, resource);
                        context.response()
                                .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                                .putHeader(HttpHeaders.PRAGMA, "no-cache")
                                .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                                .putHeader(HttpHeaders.LOCATION, resourceLocation)
                                .setStatusCode(HttpStatusCode.CREATED_201)
                                .end(Json.encodePrettily(ResourceResponse.from(resource, resourceLocation)));
                    }
                    , error -> context.fail(error)
            );
}
 
Example #15
Source File: ResourceRegistrationEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
public void delete(RoutingContext context) {
    JWT accessToken = context.get(OAuth2AuthHandler.TOKEN_CONTEXT_KEY);
    Client client = context.get(OAuth2AuthHandler.CLIENT_CONTEXT_KEY);
    String resource_id = context.request().getParam(RESOURCE_ID);

    this.resourceService.delete(domain.getId(), client.getId(), accessToken.getSub(), resource_id)
            .subscribe(
                    () -> context.response()
                            .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                            .putHeader(HttpHeaders.PRAGMA, "no-cache")
                            .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                            .setStatusCode(HttpStatusCode.NO_CONTENT_204)
                            .end()
                    , error -> context.fail(error)
            );
}
 
Example #16
Source File: UserProfileApiVerticle.java    From vertx-in-action with MIT License 6 votes vote down vote up
private void fetchUser(RoutingContext ctx) {
  String username = ctx.pathParam("username");

  JsonObject query = new JsonObject()
    .put("username", username);

  JsonObject fields = new JsonObject()
    .put("_id", 0)
    .put("username", 1)
    .put("email", 1)
    .put("deviceId", 1)
    .put("city", 1)
    .put("makePublic", 1);

  mongoClient
    .rxFindOne("user", query, fields)
    .toSingle()
    .subscribe(
      json -> completeFetchRequest(ctx, json),
      err -> handleFetchError(ctx, err));
}
 
Example #17
Source File: CurrencyServiceProxy.java    From vertx-kubernetes-workshop with Apache License 2.0 6 votes vote down vote up
private void delegateWithCircuitBreaker(RoutingContext rc) {
    HttpEndpoint.rxGetWebClient(discovery, svc -> svc.getName().equals("currency-3rdparty-service"))
        .flatMap(client -> {

            // TODO
            // Use the circuit breaker (circuit) to call the service. Use the rxExecuteCommandWithFallback` method.
            // This methods takes 2 parameters: the first one if a function taking a `Future` as parameter and
            // needs to report the success or failure on this future. The second method is a function providing
            // the fallback result. You must provide a JSON object as response. For the fallback use:
            // new JsonObject()
            //      .put("amount", rc.getBodyAsJson().getDouble("amount"))
            //      .put("currency", "USD"))
            // In the first function, use the given client, emit a POST request on / containing the incoming
            // payload (rc.getBodyAsJson()). Extract the response payload as JSON (bodyAsJsonObject). Don't
            // forget to subscribe (you can use subscribe(toObserver(fut)). You can have a look to the `delegate`
            // method as example.
            // -----
            return Single.just(new JsonObject().put("amount", 0.0).put("currency", "N/A"));
        })
        // ----
        .map(JsonObject::toBuffer)
        .map(Buffer::new)

        .subscribe(toObserver(rc));
}
 
Example #18
Source File: AuthorizationRequestValidateParametersHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    final String redirectUri = context.request().getParam(Parameters.REDIRECT_URI);
    final String responseType = context.request().getParam(Parameters.RESPONSE_TYPE);

    Client client = context.get(CLIENT_CONTEXT_KEY);

    // Additional check
    try {
        checkGrantTypes(client);
        checkResponseType(responseType, client);
        checkRedirectUri(redirectUri, client);

        context.next();
    } catch (Exception ex) {
        context.fail(ex);
    }
}
 
Example #19
Source File: LoginCallbackFailureHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    if (routingContext.failed()) {
        Throwable throwable = routingContext.failure();
        if (throwable instanceof OAuth2Exception
                || throwable instanceof AbstractManagementException
                || throwable instanceof AuthenticationException) {
            redirectToLoginPage(routingContext, throwable);
        } else {
            logger.error(throwable.getMessage(), throwable);
            if (routingContext.statusCode() != -1) {
                routingContext
                        .response()
                        .setStatusCode(routingContext.statusCode())
                        .end();
            } else {
                routingContext
                        .response()
                        .setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500)
                        .end();
            }
        }
    }
}
 
Example #20
Source File: MFAEnrollStep.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private boolean isUserEnrolled(RoutingContext routingContext, io.gravitee.am.model.User user, Client client) {
    if (routingContext.session().get(ENROLLED_FACTOR_KEY) != null) {
        return true;
    }

    if (user.getFactors() == null || user.getFactors().isEmpty()) {
        return false;
    }

    return user.getFactors()
            .stream()
            .map(enrolledFactor -> enrolledFactor.getFactorId())
            .anyMatch(f -> client.getFactors().contains(f));
}
 
Example #21
Source File: UserConsentEndpointHandler.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve specific consent for a user
 */
public void get(RoutingContext context) {
    final String consentId = context.request().getParam("consentId");
    userService.consent(consentId)
            .subscribe(
                    scopeApproval -> context.response()
                            .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                            .putHeader(HttpHeaders.PRAGMA, "no-cache")
                            .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                            .end(Json.encodePrettily(scopeApproval)),
                    error -> context.fail(error));
}
 
Example #22
Source File: AuthorizationRequestParseRequestObjectHandler.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private Maybe<JWT> handleRequestObjectValue(RoutingContext context) {
    final String request = context.request().getParam(Parameters.REQUEST);

    if (request != null) {
        // Ensure that the request_uri is not propagated to the next authorization flow step
        context.request().params().remove(Parameters.REQUEST);

        return requestObjectService
                .readRequestObject(request, context.get(CLIENT_CONTEXT_KEY))
                .toMaybe();
    } else {
        return Maybe.empty();
    }
}
 
Example #23
Source File: CurrencyServiceProxy.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
private void delegateWithCircuitBreaker(RoutingContext rc) {
    HttpEndpoint.rxGetWebClient(discovery, svc -> svc.getName().equals("currency-3rdparty-service"))
        .flatMap(client ->

            // TODO
            // Use the circuit breaker (circuit) to call the service. Use the rxExecuteCommandWithFallback` method.
            // This methods takes 2 parameters: the first one if a function taking a `Future` as parameter and
            // needs to report the success or failure on this future. The second method is a function providing
            // the fallback result. You must provide a JSON object as response. For the fallback use:
            // new JsonObject()
            //      .put("amount", rc.getBodyAsJson().getDouble("amount"))
            //      .put("currency", "USD"))
            // In the first function, use the given client, emit a POST request on / containing the incoming
            // payload (rc.getBodyAsJson()). Extract the response payload as JSON (bodyAsJsonObject). Don't
            // forget to subscribe (you can use subscribe(toObserver(fut)). You can have a look to the `delegate`
            // method as example.
            // -----
            circuit.rxExecuteCommandWithFallback(
                fut ->
                    client.post("/").rxSendJsonObject(rc.getBodyAsJson())
                        .map(HttpResponse::bodyAsJsonObject)
                        .subscribe(toObserver(fut)),
                err -> new JsonObject()
                    .put("amount", rc.getBodyAsJson().getDouble("amount"))
                    .put("currency", "USD")))

        // ----
        .map(JsonObject::toBuffer)
        .map(Buffer::new)

        .subscribe(toObserver(rc));
}
 
Example #24
Source File: RestApiUtil.java    From vertx-postgresql-starter with MIT License 5 votes vote down vote up
public static <T> T decodeBodyToObject(RoutingContext routingContext, Class<T> clazz) {
  try {
    return Json.decodeValue(routingContext.getBodyAsString("UTF-8"), clazz);
  } catch (DecodeException exception) {
    routingContext.fail(exception);
    return null;
  }
}
 
Example #25
Source File: MyFirstVerticle.java    From introduction-to-eclipse-vertx with Apache License 2.0 5 votes vote down vote up
private void updateOne(RoutingContext rc) {
    String id = rc.request().getParam("id");
    Article article = rc.getBodyAsJson().mapTo(Article.class);
    connect()
        .flatMapCompletable(connection -> update(connection, id, article))
        .subscribe(noContent(rc), onError(rc));
}
 
Example #26
Source File: AuthorizationRequestParseRequiredParametersHandler.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private void parseNonceParameter(RoutingContext context) {
    String nonce = context.request().getParam(io.gravitee.am.common.oidc.Parameters.NONCE);
    String responseType = context.request().getParam(Parameters.RESPONSE_TYPE);
    // nonce parameter is required for the Hybrid flow
    if (nonce == null && requireNonce(responseType)) {
        throw new InvalidRequestException("Missing parameter: nonce is required for Implicit and Hybrid Flow");
    }
}
 
Example #27
Source File: SuperHeroesService.java    From rxjava2-lab with Apache License 2.0 5 votes vote down vote up
private void getRandomVillain(RoutingContext rc) {
    List<Character> h = new ArrayList<>(villains.values());
    int index = random.nextInt(h.size());
    Character villain = h.get(index);
    if (verbose) {
        System.out.println("Selected villain " + villain);
    }
    rc.response().end(villain.toJson().encodePrettily());
}
 
Example #28
Source File: RestfulApiVerticle.java    From vertx-blueprint-todo-backend with Apache License 2.0 5 votes vote down vote up
protected <T> void sendResponse(RoutingContext context, Single<T> asyncResult,
                                Function<T, String> converter, BiConsumer<RoutingContext, String> f) {
  if (asyncResult == null) {
    internalError(context, "invalid_status");
  } else {
    asyncResult.subscribe(r -> f.accept(context, converter.apply(r)), ex -> internalError(context, ex));
  }
}
 
Example #29
Source File: FakeUserService.java    From vertx-in-action with MIT License 5 votes vote down vote up
private void owns(RoutingContext ctx) {
  logger.info("Device ownership request {}", ctx.request().path());
  deviceId = ctx.pathParam("deviceId");
  JsonObject notAllData = new JsonObject()
    .put("username", "Foo")
    .put("deviceId", deviceId);
  ctx.response()
    .putHeader("Content-Type", "application/json")
    .end(notAllData.encode());
}
 
Example #30
Source File: Helpers.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
/**
 * Utility method to report the completion/failure from a Single to a Routing Context.
 *
 * @param rc the routing context
 * @return the single observer to pass to {@link Single#subscribe()}
 */
public static SingleObserver<Buffer> toObserver(RoutingContext rc) {
    return new SingleObserver<Buffer>() {
        public void onSubscribe(@NonNull Disposable d) {
        }

        public void onSuccess(@NonNull Buffer payload) {
            rc.response().end(payload);
        }

        public void onError(Throwable error) {
            rc.fail(error);
        }
    };
}