Example usage for io.vertx.core.http HttpClient requestAbs

List of usage examples for io.vertx.core.http HttpClient requestAbs

Introduction

In this page you can find the example usage for io.vertx.core.http HttpClient requestAbs.

Prototype

HttpClientRequest requestAbs(HttpMethod method, String absoluteURI);

Source Link

Document

Create an HTTP request to send to the server using an absolute URI

Usage

From source file:io.gravitee.resource.oauth2.generic.OAuth2GenericResource.java

License:Apache License

@Override
public void introspect(String accessToken, Handler<OAuth2Response> responseHandler) {
    HttpClient httpClient = httpClients.computeIfAbsent(Vertx.currentContext(),
            context -> vertx.createHttpClient(httpClientOptions));

    OAuth2ResourceConfiguration configuration = configuration();
    StringBuilder introspectionUriBuilder = new StringBuilder(introspectionEndpointURI);

    if (configuration.isTokenIsSuppliedByQueryParam()) {
        introspectionUriBuilder.append('?').append(configuration.getTokenQueryParamName()).append('=')
                .append(accessToken);//from  w  ww  .j ava 2s.  c o m
    }

    String introspectionEndpointURI = introspectionUriBuilder.toString();
    logger.debug("Introspect access token by requesting {} [{}]", introspectionEndpointURI,
            configuration.getIntrospectionEndpointMethod());

    HttpMethod httpMethod = HttpMethod.valueOf(configuration.getIntrospectionEndpointMethod().toUpperCase());

    HttpClientRequest request = httpClient.requestAbs(httpMethod, introspectionEndpointURI);
    request.setTimeout(30000L);

    if (configuration().isUseClientAuthorizationHeader()) {
        String authorizationHeader = configuration.getClientAuthorizationHeaderName();
        String authorizationValue = configuration.getClientAuthorizationHeaderScheme().trim()
                + AUTHORIZATION_HEADER_SCHEME_SEPARATOR
                + Base64.getEncoder().encodeToString(
                        (configuration.getClientId() + AUTHORIZATION_HEADER_VALUE_BASE64_SEPARATOR
                                + configuration.getClientSecret()).getBytes());
        request.headers().add(authorizationHeader, authorizationValue);
        logger.debug("Set client authorization using HTTP header {} with value {}", authorizationHeader,
                authorizationValue);
    }

    // Set `Accept` header to ask for application/json content
    request.headers().add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);

    if (configuration.isTokenIsSuppliedByHttpHeader()) {
        request.headers().add(configuration.getTokenHeaderName(), accessToken);
    }

    request.handler(response -> response.bodyHandler(buffer -> {
        logger.debug("Introspection endpoint returns a response with a {} status code", response.statusCode());
        if (response.statusCode() == HttpStatusCode.OK_200) {
            // According to RFC 7662 : Note that a properly formed and authorized query for an inactive or
            // otherwise invalid token (or a token the protected resource is not
            // allowed to know about) is not considered an error response by this
            // specification.  In these cases, the authorization server MUST instead
            // respond with an introspection response with the "active" field set to
            // "false" as described in Section 2.2.
            String content = buffer.toString();

            try {
                JsonNode introspectNode = MAPPER.readTree(content);
                JsonNode activeNode = introspectNode.get("active");
                if (activeNode != null) {
                    boolean isActive = activeNode.asBoolean();
                    responseHandler.handle(new OAuth2Response(isActive, content));
                } else {
                    responseHandler.handle(new OAuth2Response(true, content));
                }
            } catch (IOException e) {
                logger.error("Unable to validate introspection endpoint payload: {}", content);
                responseHandler.handle(new OAuth2Response(false, content));
            }
        } else {
            responseHandler.handle(new OAuth2Response(false, buffer.toString()));
        }
    }));

    request.exceptionHandler(event -> {
        logger.error("An error occurs while checking OAuth2 token", event);
        responseHandler.handle(new OAuth2Response(false, event.getMessage()));
    });

    if (httpMethod == HttpMethod.POST && configuration.isTokenIsSuppliedByFormUrlEncoded()) {
        request.headers().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
        request.end(configuration.getTokenFormUrlEncodedName() + '=' + accessToken);
    } else {
        request.end();
    }
}

From source file:io.gravitee.resource.oauth2.generic.OAuth2GenericResource.java

License:Apache License

@Override
public void userInfo(String accessToken, Handler<UserInfoResponse> responseHandler) {
    HttpClient httpClient = httpClients.computeIfAbsent(Vertx.currentContext(),
            context -> vertx.createHttpClient(httpClientOptions));

    OAuth2ResourceConfiguration configuration = configuration();

    HttpMethod httpMethod = HttpMethod.valueOf(configuration.getUserInfoEndpointMethod().toUpperCase());

    logger.debug("Get userinfo by requesting {} [{}]", userInfoEndpointURI,
            configuration.getUserInfoEndpointMethod());

    HttpClientRequest request = httpClient.requestAbs(httpMethod, userInfoEndpointURI);

    request.headers().add(HttpHeaders.AUTHORIZATION, AUTHORIZATION_HEADER_BEARER_SCHEME + accessToken);

    request.handler(response -> response.bodyHandler(buffer -> {
        logger.debug("Userinfo endpoint returns a response with a {} status code", response.statusCode());

        if (response.statusCode() == HttpStatusCode.OK_200) {
            responseHandler.handle(new UserInfoResponse(true, buffer.toString()));
        } else {//from  ww w. j a va2s .  co m
            responseHandler.handle(new UserInfoResponse(false, buffer.toString()));
        }
    }));

    request.exceptionHandler(event -> {
        logger.error("An error occurs while getting userinfo from access_token", event);
        responseHandler.handle(new UserInfoResponse(false, event.getMessage()));
    });

    request.end();
}