io.gravitee.common.http.HttpHeaders Java Examples

The following examples show how to use io.gravitee.common.http.HttpHeaders. 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: DynamicClientAccessEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
/**
 * Read client_metadata.
 * See <a href="https://openid.net/specs/openid-connect-registration-1_0.html#ReadRequest">Read Request</a>
 * See <a href="https://openid.net/specs/openid-connect-registration-1_0.html#ReadResponse">Read Response</a>
 *
 * @param context
 */
public void read(RoutingContext context) {
    LOGGER.debug("Dynamic client registration GET endpoint");

    this.getClient(context)
            .map(DynamicClientRegistrationResponse::fromClient)
            .map(response -> {
                //The Authorization Server need not include the registration access_token or client_uri unless they have been updated.
                response.setRegistrationAccessToken(null);
                response.setRegistrationClientUri(null);
                return response;
            })
            .subscribe(
                    result -> 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(result))
                    , error -> context.fail(error)
            );
}
 
Example #2
Source File: ClientBasicAuthProviderTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAuthenticateClient() throws Exception {
    Client client = mock(Client.class);
    when(client.getClientId()).thenReturn("my-client-id");
    when(client.getClientSecret()).thenReturn("my-client-secret");

    HttpServerRequest httpServerRequest = mock(HttpServerRequest.class);
    VertxHttpHeaders vertxHttpHeaders = new VertxHttpHeaders();
    vertxHttpHeaders.add(HttpHeaders.AUTHORIZATION, "Basic bXktY2xpZW50LWlkOm15LWNsaWVudC1zZWNyZXQ=");
    when(httpServerRequest.headers()).thenReturn(MultiMap.newInstance(vertxHttpHeaders));

    CountDownLatch latch = new CountDownLatch(1);
    authProvider.handle(client, httpServerRequest, clientAsyncResult -> {
        latch.countDown();
        Assert.assertNotNull(clientAsyncResult);
        Assert.assertNotNull(clientAsyncResult.result());
    });

    assertTrue(latch.await(10, TimeUnit.SECONDS));
}
 
Example #3
Source File: UserInfoEndpointHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInvokeUserEndpoint_noOpenIDScope_noScope() throws Exception {
    JWT jwt = new JWT();
    jwt.setJti("id-token");
    jwt.setAud("client-id");
    jwt.setSub("id-subject");

    Client client = new Client();
    client.setId("client-id");
    client.setClientId("client-id");

    router.route().order(-1).handler(createOAuth2AuthHandler(oAuth2AuthProvider(jwt, client)));

    testRequest(
            HttpMethod.GET, "/userinfo", req -> req.putHeader(HttpHeaders.AUTHORIZATION, "Bearer test-token"),
            HttpStatusCode.FORBIDDEN_403, "Forbidden", null);
}
 
Example #4
Source File: ApiKeysServiceHandler.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext ctx) {
    HttpServerResponse response = ctx.response();
    response.setStatusCode(HttpStatusCode.OK_200);
    response.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    response.setChunked(true);

    try {
        Json.prettyMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        response.write(Json.prettyMapper.writeValueAsString(new ExecutorStatistics()));
    } catch (JsonProcessingException jpe) {
        response.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500);
        LOGGER.error("Unable to transform data object to JSON", jpe);
    }

    response.end();
}
 
Example #5
Source File: XForwardForProcessorTest.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void test_with_one_X_Forward_for_in_Header_withIPv6() throws InterruptedException {
    final CountDownLatch lock = new CountDownLatch(1);

    when(headers.getFirst(HttpHeaders.X_FORWARDED_FOR)).thenReturn("2001:0db8:85a3:0000:0000:8a2e:0370:7334");
    when(request.remoteAddress()).thenReturn("192.168.0.1");

    new XForwardForProcessor()
            .handler(context -> {
                Assert.assertTrue(context.request() instanceof XForwardForRequest);
                Assert.assertEquals("2001:0db8:85a3:0000:0000:8a2e:0370:7334", context.request().remoteAddress());
                Assert.assertEquals("2001:0db8:85a3:0000:0000:8a2e:0370:7334", context.request().metrics().getRemoteAddress());
                lock.countDown();
            })
            .handle(context);

    Assert.assertTrue(lock.await(10000, TimeUnit.MILLISECONDS));
}
 
Example #6
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 #7
Source File: UserConsentEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    final Session session = routingContext.session();
    final Client client = routingContext.get(CLIENT_CONTEXT_KEY);
    final Set<String> requiredConsent = session.get(REQUESTED_CONSENT_CONTEXT_KEY);

    // fetch scope information (name + description)
    fetchConsentInformation(requiredConsent, h -> {
        if (h.failed()) {
            routingContext.fail(h.cause());
            return;
        }
        List<Scope> requestedScopes = h.result();
        routingContext.put(SCOPES_CONTEXT_KEY, requestedScopes);
        engine.render(routingContext.data(), getTemplateFileName(client), res -> {
            if (res.succeeded()) {
                routingContext.response().putHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML);
                routingContext.response().end(res.result());
            } else {
                logger.error("Unable to render user consent page", res.cause());
                routingContext.fail(res.cause());
            }
        });
    });
}
 
Example #8
Source File: ErrorHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private void handleException(RoutingContext routingContext, int httpStatusCode, String errorDetail, ScimType scimType) {
    Error error = new Error();
    error.setStatus(String.valueOf(httpStatusCode));
    error.setDetail(errorDetail);
    if (scimType != null) {
        error.setScimType(scimType.value());
    } else if(httpStatusCode == HttpStatusCode.BAD_REQUEST_400) {
        error.setScimType(ScimType.INVALID_VALUE.value());
    }
    routingContext
            .response()
            .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
            .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
            .putHeader(HttpHeaders.PRAGMA, "no-cache")
            .setStatusCode(httpStatusCode)
            .end(Json.encodePrettily(error));
}
 
Example #9
Source File: ApiKeyAuthenticationHandlerTest.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldHandleRequestUsingQueryParameters() throws TechnicalException {
    when(authenticationContext.request()).thenReturn(request);
    when(request.metrics()).thenReturn(metrics);
    MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
    parameters.put("api-key", Collections.singletonList("xxxxx-xxxx-xxxxx"));
    when(request.parameters()).thenReturn(parameters);
    when(apiKeyRepository.findById("xxxxx-xxxx-xxxxx")).thenReturn(of(new ApiKey()));

    HttpHeaders headers = new HttpHeaders();
    when(request.headers()).thenReturn(headers);

    boolean handle = authenticationHandler.canHandle(authenticationContext);
    Assert.assertTrue(handle);
    verify(metrics).setSecurityType(SecurityType.API_KEY);
    verify(metrics).setSecurityToken("xxxxx-xxxx-xxxxx");
}
 
Example #10
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 #11
Source File: PermissionEndpointTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void success_extendedRequest() {
    PermissionTicket success = new PermissionTicket().setId("success");
    final String extendedRequest = "[{\"resource_id\":\"{{set_one}}\", \"resource_scopes\":[\"profile:read\"]}, {\"resource_id\":\"{{set_two}}\",\"resource_scopes\":[\"avatar:write\"]}]";

    when(context.getBody()).thenReturn(Buffer.buffer(extendedRequest));
    when(context.response()).thenReturn(response);
    when(response.putHeader(anyString(),anyString())).thenReturn(response);
    when(response.setStatusCode(anyInt())).thenReturn(response);
    when(permissionTicketService.create(anyList(), eq(DOMAIN_ID), eq(CLIENT_ID))).thenReturn(Single.just(success));
    endpoint.handle(context);
    verify(response, times(1)).putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    verify(context.response(), times(1)).setStatusCode(intCaptor.capture());
    verify(context.response(), times(1)).end(strCaptor.capture());
    Assert.assertEquals("Expecting 201 creation status",intCaptor.getValue().intValue(),201);
    Assert.assertTrue("Expect success id", strCaptor.getValue().contains("success"));
}
 
Example #12
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 #13
Source File: ResourceRegistrationEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    JWT accessToken = context.get(OAuth2AuthHandler.TOKEN_CONTEXT_KEY);
    Client client = context.get(OAuth2AuthHandler.CLIENT_CONTEXT_KEY);

    this.resourceService.listByDomainAndClientAndUser(domain.getId(), client.getId(), accessToken.getSub())
            .flatMapPublisher(Flowable::fromIterable)
            .map(Resource::getId)
            .collect(JsonArray::new, JsonArray::add)
            .subscribe(
                    buffer -> context.response()
                            .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                            .putHeader(HttpHeaders.PRAGMA, "no-cache")
                            .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                            .setStatusCode(buffer.isEmpty()?HttpStatusCode.NO_CONTENT_204:HttpStatusCode.OK_200)
                            .end(Json.encodePrettily(buffer))
                    , error -> context.fail(error)
            );
}
 
Example #14
Source File: UserInfoEndpointHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInvokeUserEndpoint_noOpenIDScope() throws Exception {
    JWT jwt = new JWT();
    jwt.setJti("id-token");
    jwt.setAud("client-id");
    jwt.setSub("id-subject");
    jwt.setScope("read");

    Client client = new Client();
    client.setId("client-id");
    client.setClientId("client-id");

    router.route().order(-1).handler(createOAuth2AuthHandler(oAuth2AuthProvider(jwt, client)));

    testRequest(
            HttpMethod.GET, "/userinfo", req -> req.putHeader(HttpHeaders.AUTHORIZATION, "Bearer test-token"),
            HttpStatusCode.FORBIDDEN_403, "Forbidden", null);
}
 
Example #15
Source File: DynamicClientAccessEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
/**
 * Update/Override client_metadata.
 * @param context
 */
public void update(RoutingContext context) {
    LOGGER.debug("Dynamic client registration UPDATE endpoint");

    this.getClient(context)
            .flatMapSingle(Single::just)
            .flatMap(client -> this.extractRequest(context)
                    .flatMap(request -> dcrService.update(client, request, UriBuilderRequest.extractBasePath(context)))
                    .map(clientSyncService::addDynamicClientRegistred)
            )
            .subscribe(
                    client -> 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(DynamicClientRegistrationResponse.fromClient(client)))
                    , error -> context.fail(error)
            );
}
 
Example #16
Source File: XForwardForProcessorTest.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void test_with_one_X_Forward_for_in_Header_withIPv6_hexadecimalFormat() throws InterruptedException {
    final CountDownLatch lock = new CountDownLatch(1);

    when(headers.getFirst(HttpHeaders.X_FORWARDED_FOR)).thenReturn("2001:db8:85a3:0:0:8a2e:370:7334");
    when(request.remoteAddress()).thenReturn("192.168.0.1");

    new XForwardForProcessor()
            .handler(context -> {
                Assert.assertTrue(context.request() instanceof XForwardForRequest);
                Assert.assertEquals("2001:db8:85a3:0:0:8a2e:370:7334", context.request().remoteAddress());
                Assert.assertEquals("2001:db8:85a3:0:0:8a2e:370:7334", context.request().metrics().getRemoteAddress());
                lock.countDown();
            })
            .handle(context);

    Assert.assertTrue(lock.await(10000, TimeUnit.MILLISECONDS));
}
 
Example #17
Source File: DynamicClientAccessEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
/**
 * Renew client_secret
 * @param context
 */
public void renewClientSecret(RoutingContext context) {
    LOGGER.debug("Dynamic client registration RENEW SECRET endpoint");

    this.getClient(context)
            .flatMapSingle(Single::just)
            .flatMap(toRenew -> dcrService.renewSecret(toRenew, UriBuilderRequest.extractBasePath(context)))
            .map(clientSyncService::addDynamicClientRegistred)
            .subscribe(
                    client -> 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(DynamicClientRegistrationResponse.fromClient(client)))
                    , error -> context.fail(error)
            );
}
 
Example #18
Source File: CheckSubscriptionPolicyTest.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnUnauthorized_noClient() throws PolicyException, TechnicalException {
    CheckSubscriptionPolicy policy = new CheckSubscriptionPolicy();

    Response response = mock(Response.class);
    when(response.headers()).thenReturn(mock(HttpHeaders.class));
    PolicyChain policyChain = mock(PolicyChain.class);

    ExecutionContext executionContext = mock(ExecutionContext.class);

    SubscriptionRepository subscriptionRepository = mock(SubscriptionRepository.class);
    when(executionContext.getComponent(SubscriptionRepository.class)).thenReturn(subscriptionRepository);

    policy.onRequest(request, response, policyChain, executionContext);

    verify(policyChain, times(1)).failWith(argThat(
            result -> result.statusCode() == HttpStatusCode.UNAUTHORIZED_401
                    && CheckSubscriptionPolicy.GATEWAY_OAUTH2_INVALID_CLIENT_KEY.equals(result.key())));
}
 
Example #19
Source File: PermissionEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    JWT accessToken = context.get(OAuth2AuthHandler.TOKEN_CONTEXT_KEY);
    Client client = context.get(OAuth2AuthHandler.CLIENT_CONTEXT_KEY);

    this.extractRequest(context)
            .flatMap(this::bodyValidation)
            .map(this::toPermissionRequest)
            .flatMap(permissionRequests -> permissionTicketService.create(permissionRequests, domain.getId(), client.getId()))
            .map(PermissionTicketResponse::from)
            .subscribe(
                    permission -> context.response()
                            .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                            .putHeader(HttpHeaders.PRAGMA, "no-cache")
                            .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                            .setStatusCode(HttpStatusCode.CREATED_201)
                            .end(Json.encodePrettily(permission))
                    , error -> context.fail(error)
            );
}
 
Example #20
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 #21
Source File: ResourceAccessPoliciesEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
public void update(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);

    // extract access policy payload
    AccessPolicy accessPolicy = extractRequest(context);

    // update the access policy
    resourceService.updateAccessPolicy(accessPolicy, domain.getId(), client.getId(), accessToken.getSub(), resource, 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 #22
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 #23
Source File: TokenExtractorTest.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldExtract_fromQueryParameter() {
    String jwt = "dummy-token";

    HttpHeaders headers = new HttpHeaders();
    when(request.headers()).thenReturn(headers);

    LinkedMultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
    parameters.add(TokenExtractor.ACCESS_TOKEN, jwt);
    when(request.parameters()).thenReturn(parameters);

    String token = TokenExtractor.extract(request);

    Assert.assertNotNull(token);
    Assert.assertEquals(jwt, token);
}
 
Example #24
Source File: VertxHttpServerResponse.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public Response write(Buffer chunk) {
    if (valid()) {
        if (!httpServerResponse.headWritten()) {
            writeHeaders();

            // Vertx requires to set the chunked flag if transfer_encoding header as the "chunked" value
            String transferEncodingHeader = headers().getFirst(HttpHeaders.TRANSFER_ENCODING);
            if (HttpHeadersValues.TRANSFER_ENCODING_CHUNKED.equalsIgnoreCase(transferEncodingHeader)) {
                httpServerResponse.setChunked(true);
            } else if (transferEncodingHeader == null) {
                String connectionHeader = headers().getFirst(HttpHeaders.CONNECTION);
                String contentLengthHeader = headers().getFirst(HttpHeaders.CONTENT_LENGTH);
                if (HttpHeadersValues.CONNECTION_CLOSE.equalsIgnoreCase(connectionHeader)
                        && contentLengthHeader == null) {
                    httpServerResponse.setChunked(true);
                }
            }
        }

        metrics.setResponseContentLength(metrics.getResponseContentLength() + chunk.length());
        httpServerResponse.write(io.vertx.core.buffer.Buffer.buffer((ByteBuf) chunk.getNativeBuffer()));
    }
    return this;
}
 
Example #25
Source File: UserInfoEndpointHandlerTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldInvokeUserEndpoint_scopesRequest_and_claimsRequest_signedResponse() throws Exception {
    JWT jwt = new JWT();
    jwt.setJti("id-token");
    jwt.setAud("client-id");
    jwt.setSub("id-subject");
    jwt.setScope("openid email address");
    jwt.setClaimsRequestParameter("{\"userinfo\":{\"name\":{\"essential\":true}}}");

    Client client = new Client();
    client.setId("client-id");
    client.setClientId("client-id");
    client.setUserinfoSignedResponseAlg("algorithm");

    router.route().order(-1).handler(createOAuth2AuthHandler(oAuth2AuthProvider(jwt, client)));

    User user = createUser();

    when(userService.findById(anyString())).thenReturn(Maybe.just(user));
    when(jwtService.encodeUserinfo(any(),any())).thenReturn(Single.just("signedJwtBearer"));
    when(jweService.encryptUserinfo("signedJwtBearer",client)).thenReturn(Single.just("signedJwtBearer"));

    testRequest(
            HttpMethod.GET,
            "/userinfo",
            req -> req.putHeader(HttpHeaders.AUTHORIZATION, "Bearer test-token"),
            resp -> {
                assertEquals(MediaType.APPLICATION_JWT,resp.getHeader(HttpHeaders.CONTENT_TYPE));
                resp.bodyHandler(body -> assertEquals("signedJwtBearer",body.toString()));
            },
            HttpStatusCode.OK_200, "OK", null);
}
 
Example #26
Source File: ResourceRegistrationEndpointTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void update_withResource() {
    when(context.getBodyAsJson()).thenReturn(new JsonObject("{\"id\":\"rs_id\",\"resource_scopes\":[\"scope\"]}"));
    when(service.update(any() , eq(DOMAIN_ID), eq(CLIENT_ID), eq(USER_ID), eq(RESOURCE_ID))).thenReturn(Single.just(new Resource()));
    endpoint.update(context);
    verify(response, times(1)).putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    verify(response, times(1)).setStatusCode(intCaptor.capture());
    Assert.assertEquals("Should be ok",200, intCaptor.getValue().intValue());
}
 
Example #27
Source File: OAuth2AuthenticationHandlerTest.java    From gravitee-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotHandleRequest_noAuthorizationHeader() {
    when(request.headers()).thenReturn(new HttpHeaders());

    boolean handle = authenticationHandler.canHandle(authenticationContext);
    Assert.assertFalse(handle);
}
 
Example #28
Source File: RevocationTokenEndpointTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotInvokeRevocationTokenEndpoint_noClient() throws Exception {
    testRequest(
            HttpMethod.POST, "/oauth/revoke",
            req -> req.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED),
            HttpStatusCode.UNAUTHORIZED_401, "Unauthorized", null);
}
 
Example #29
Source File: DynamicClientRegistrationTemplateEndpoint.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    LOGGER.debug("Dynamic client registration TEMPLATE endpoint");

    this.clientSyncService.findTemplates()
            .subscribe(
                    templates -> 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(DynamicClientRegistrationTemplate.from(templates)))
                    , error -> context.fail(error)
            );
}
 
Example #30
Source File: CorsRegexTest.java    From gravitee-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void preflight_request() throws Exception {
    HttpResponse response = Request.Options("http://localhost:8082/test/my_team")
            .addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.GET.name())
            .addHeader(HttpHeaders.ORIGIN, "http://api.mycompany.com")
            .execute().returnResponse();

    assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());

    wireMockRule.verify(0, optionsRequestedFor(urlEqualTo("/team/my_team")));
}