io.vertx.reactivex.core.http.HttpServerRequest Java Examples

The following examples show how to use io.vertx.reactivex.core.http.HttpServerRequest. 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: ClientAssertionAuthProviderTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void unauthorized_invalidClient_clientDoesNotMatch() throws Exception {
    Client client = Mockito.mock(Client.class);
    when(client.getClientId()).thenReturn(CLIENT_ID);
    when(clientAssertionService.assertClient(any(),any(),any())).thenReturn(Maybe.just(client));

    HttpServerRequest httpServerRequest = mock(HttpServerRequest.class);
    when(httpServerRequest.getParam(Parameters.CLIENT_ASSERTION_TYPE)).thenReturn("unknown");
    when(httpServerRequest.getParam(Parameters.CLIENT_ASSERTION)).thenReturn("dummy");
    when(httpServerRequest.getParam(Parameters.CLIENT_ID)).thenReturn("notMatching");


    CountDownLatch latch = new CountDownLatch(1);
    authProvider.handle(client, httpServerRequest, clientAsyncResult -> {
        latch.countDown();
        Assert.assertNotNull(clientAsyncResult);
        Assert.assertTrue(clientAsyncResult.failed());
        Assert.assertTrue(clientAsyncResult.cause() instanceof InvalidClientException);
    });

    assertTrue(latch.await(10, TimeUnit.SECONDS));
}
 
Example #2
Source File: ClientCertificateAuthProvider.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Client client, HttpServerRequest request, Handler<AsyncResult<Client>> handler) {
    // We ensure that the authentication is done over TLS thanks to the canHandle method which checks for an SSL
    // session
    SSLSession sslSession = request.sslSession();

    try {
        Certificate[] peerCertificates = sslSession.getPeerCertificates();
        X509Certificate peerCertificate = (X509Certificate) peerCertificates[0];

        if ((client.getTlsClientAuthSubjectDn() != null && validateSubjectDn(client, peerCertificate)) ||
                (client.getTlsClientAuthSanDns() != null && validateSAN(peerCertificate, GeneralName.dNSName, client.getTlsClientAuthSanDns())) ||
                (client.getTlsClientAuthSanEmail() != null && validateSAN(peerCertificate, GeneralName.rfc822Name, client.getTlsClientAuthSanEmail())) ||
                (client.getTlsClientAuthSanIp() != null && validateSAN(peerCertificate, GeneralName.iPAddress, client.getTlsClientAuthSanIp())) ||
                (client.getTlsClientAuthSanUri() != null && validateSAN(peerCertificate, GeneralName.uniformResourceIdentifier, client.getTlsClientAuthSanUri()))) {
            handler.handle(Future.succeededFuture(client));
        } else {
            handler.handle(Future.failedFuture(new InvalidClientException("Invalid client: missing TLS configuration")));
        }
    } catch (SSLPeerUnverifiedException | CertificateParsingException ce) {
        handler.handle(Future.failedFuture(new InvalidClientException("Invalid client: missing or unsupported certificate")));
    }
}
 
Example #3
Source File: ApiResource.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@RequiresPermissions("update")
@PUT
@Path("pages/{id}")
public Single<Response> apiUpdatePage(@PathParam("id") String id, 
		@ApiUpdateValid("markdown") JsonObject page,
		@Context HttpServerRequest req,
		@Context Vertx vertx){
	return Fibers.fiber(() -> {
		Optional<Pages> res = Fibers.await(dao.findOneById(Integer.valueOf(id)));
		if(!res.isPresent())
			return Response.status(Status.NOT_FOUND).build();
		Fibers.await(dao.update(res.get().setContent(page.getString("markdown"))));
		JsonObject event = new JsonObject()
				.put("id", id)
				.put("client", page.getString("client"));
		vertx.eventBus().publish("page.saved", event);
		return Response.ok(new JsonObject().put("success", true)).build();
	});
}
 
Example #4
Source File: ClientAssertionAuthProviderTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void unauthorized_invalidClient_assertion_type() throws Exception {
    Client client = mock(Client.class);
    HttpServerRequest httpServerRequest = mock(HttpServerRequest.class);
    when(httpServerRequest.getParam(Parameters.CLIENT_ASSERTION_TYPE)).thenReturn("unknown");
    when(httpServerRequest.getParam(Parameters.CLIENT_ASSERTION)).thenReturn("dummy");

    when(clientAssertionService.assertClient(any(),any(),any())).thenReturn(Maybe.error(new InvalidClientException("Unknown or unsupported assertion_type")));

    CountDownLatch latch = new CountDownLatch(1);
    authProvider.handle(client, httpServerRequest, clientAsyncResult -> {
        latch.countDown();
        Assert.assertNotNull(clientAsyncResult);
        Assert.assertTrue(clientAsyncResult.failed());
        Assert.assertTrue(clientAsyncResult.cause() instanceof InvalidClientException);
    });

    assertTrue(latch.await(10, TimeUnit.SECONDS));
}
 
Example #5
Source File: ClientCertificateAuthProviderTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void authorized_client() throws Exception {
    Client client = mock(Client.class);
    HttpServerRequest httpServerRequest = mock(HttpServerRequest.class);
    SSLSession sslSession = mock(SSLSession.class);

    X509Certificate certificate = mock(X509Certificate.class);
    Principal subjectDN = mock(Principal.class);

    when(client.getTlsClientAuthSubjectDn()).thenReturn("CN=localhost, O=GraviteeSource, C=FR");
    when(subjectDN.getName()).thenReturn("CN=localhost, O=GraviteeSource, C=FR");
    when(certificate.getSubjectDN()).thenReturn(subjectDN);
    when(httpServerRequest.sslSession()).thenReturn(sslSession);
    when(sslSession.getPeerCertificates()).thenReturn(new Certificate[]{certificate});

    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 #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: ApiResource.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@RequiresPermissions("update")
@PUT
@Path("pages/{id}")
public Single<Response> apiUpdatePage(@PathParam("id") String id, 
		@ApiUpdateValid("markdown") JsonObject page,
		@Context HttpServerRequest req,
		@Context Vertx vertx){
	JsonArray params = new JsonArray();
	params.add(page.getString("markdown")).add(id);
	return SQLUtil.doInConnection(connection -> connection.rxUpdateWithParams(SQL.SQL_SAVE_PAGE, params))
			.map(res -> {
			    JsonObject event = new JsonObject()
			    	      .put("id", id)
			    	      .put("client", page.getString("client"));
			    vertx.eventBus().publish("page.saved", event);
				return Response.ok(new JsonObject().put("success", true)).build();
			});
}
 
Example #8
Source File: ClientCertificateAuthProviderTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void unauthorized_client_SSLPeerUnverifiedException() throws Exception {
    Client client = mock(Client.class);
    HttpServerRequest httpServerRequest = mock(HttpServerRequest.class);
    SSLSession sslSession = mock(SSLSession.class);

    when(httpServerRequest.sslSession()).thenReturn(sslSession);
    when(sslSession.getPeerCertificates()).thenThrow(SSLPeerUnverifiedException.class);

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

    assertTrue(latch.await(10, TimeUnit.SECONDS));
}
 
Example #9
Source File: ClientAssertionAuthProviderTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void authorized_client() throws Exception {
    Client client = mock(Client.class);
    HttpServerRequest httpServerRequest = mock(HttpServerRequest.class);
    when(httpServerRequest.getParam(Parameters.CLIENT_ASSERTION_TYPE)).thenReturn("unknown");
    when(httpServerRequest.getParam(Parameters.CLIENT_ASSERTION)).thenReturn("dummy");

    when(clientAssertionService.assertClient(any(),any(),any())).thenReturn(Maybe.just(client));

    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 #10
Source File: DynamicClientRegistrationEndpointTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void register_success() {
    //Context
    HttpServerRequest serverRequest = Mockito.mock(HttpServerRequest.class);
    HttpServerResponse serverResponse = Mockito.mock(HttpServerResponse.class);

    when(routingContext.request()).thenReturn(serverRequest);
    when(serverRequest.getHeader(any())).thenReturn(null);
    when(serverRequest.scheme()).thenReturn("https");
    when(serverRequest.host()).thenReturn("host");
    when(routingContext.response()).thenReturn(serverResponse);
    when(serverResponse.putHeader(anyString(),anyString())).thenReturn(serverResponse);
    when(serverResponse.setStatusCode(201)).thenReturn(serverResponse);

    when(dcrService.create(any(),any())).thenReturn(Single.just(new Client()));
    when(clientSyncService.addDynamicClientRegistred(any())).thenReturn(new Client());

    //Test
    endpoint.handle(routingContext);

    //Assertions
    verify(routingContext, times(1)).response();
    verify(serverResponse,times(3)).putHeader(anyString(),anyString());
    verify(serverResponse,times(1)).end(anyString());
}
 
Example #11
Source File: ClientCertificateAuthProviderTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void unauthorized_client_noMatchingDN() throws Exception {
    Client client = mock(Client.class);
    HttpServerRequest httpServerRequest = mock(HttpServerRequest.class);
    SSLSession sslSession = mock(SSLSession.class);

    X509Certificate certificate = mock(X509Certificate.class);
    Principal subjectDN = mock(Principal.class);

    when(client.getTlsClientAuthSubjectDn()).thenReturn("CN=localhost, O=Invalid, C=US");
    when(subjectDN.getName()).thenReturn("CN=localhost, O=GraviteeSource, C=FR");
    when(certificate.getSubjectDN()).thenReturn(subjectDN);
    when(httpServerRequest.sslSession()).thenReturn(sslSession);
    when(sslSession.getPeerCertificates()).thenReturn(new Certificate[]{certificate});

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

    assertTrue(latch.await(10, TimeUnit.SECONDS));
}
 
Example #12
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 #13
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 #14
Source File: ClientPostAuthProviderTest.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);
    when(httpServerRequest.getParam(Parameters.CLIENT_ID)).thenReturn("my-client-id");
    when(httpServerRequest.getParam(Parameters.CLIENT_SECRET)).thenReturn("my-client-secret");

    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 #15
Source File: ClientBasicAuthProviderTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotAuthenticateClient_badClientSecret() 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 bXktY2xpZW50LWlkOm15LW90aGVyLWNsaWVudC1zZWNyZXQ=");
    when(httpServerRequest.headers()).thenReturn(MultiMap.newInstance(vertxHttpHeaders));

    CountDownLatch latch = new CountDownLatch(1);
    authProvider.handle(client, httpServerRequest, userAsyncResult -> {
        latch.countDown();
        Assert.assertNotNull(userAsyncResult);
        Assert.assertTrue(userAsyncResult.failed());
        Assert.assertTrue(userAsyncResult.cause() instanceof InvalidClientException);
    });

    assertTrue(latch.await(10, TimeUnit.SECONDS));
}
 
Example #16
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 #17
Source File: AuthorizationRequestEndUserConsentHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
public void redirectToConsentPage(HttpServerRequest request) {
    try {
        final Map<String, String> requestParameters = request.params().entries().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        String proxiedRedirectURI = UriBuilderRequest.resolveProxyRequest(request, redirectURL, requestParameters, true);
        request.response()
                .putHeader(HttpHeaders.LOCATION, proxiedRedirectURI)
                .setStatusCode(302)
                .end();
    } catch (Exception e) {
        LOGGER.warn("Failed to decode consent redirect url", e);
        request.response()
                .putHeader(HttpHeaders.LOCATION, redirectURL)
                .setStatusCode(302)
                .end();
    }
}
 
Example #18
Source File: RedirectHandlerImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    try {
        final HttpServerRequest request = routingContext.request();
        final Map<String, String> requestParameters = request.params().entries().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        String proxiedRedirectURI = UriBuilderRequest.resolveProxyRequest(routingContext.request(), redirectURL, requestParameters, true);
        routingContext.response()
                .putHeader(HttpHeaders.LOCATION, proxiedRedirectURI)
                .setStatusCode(302)
                .end();
    } catch (Exception e) {
        logger.warn("Failed to decode login redirect url", e);
        routingContext.response()
                .putHeader(HttpHeaders.LOCATION, redirectURL)
                .setStatusCode(302)
                .end();
    }
}
 
Example #19
Source File: ForgotPasswordEndpoint.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 error = request.getParam(ERROR_PARAM);
    final String success = request.getParam(SUCCESS_PARAM);
    final String warning = request.getParam(WARNING_PARAM);
    final Client client = routingContext.get("client");
    // add query params to context
    routingContext.put(ERROR_PARAM, error);
    routingContext.put(SUCCESS_PARAM, success);
    routingContext.put(WARNING_PARAM, warning);
    routingContext.put(PARAM_CONTEXT_KEY, Collections.singletonMap(Parameters.CLIENT_ID, request.getParam(Parameters.CLIENT_ID)));

    // render the forgot password page
    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 forgot password page", res.cause());
            routingContext.fail(res.cause());
        }
    });
}
 
Example #20
Source File: ClientAuthHandlerImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private void resolveClient(HttpServerRequest request, Handler<AsyncResult<Client>> handler) {
    // client_id can be retrieved via query parameter or Basic Authorization
    parseClientId(request, h -> {
        if (h.failed()) {
            handler.handle(Future.failedFuture(h.cause()));
            return;
        }
        final String clientId = h.result();
        // client_id can be null if client authentication method is private_jwt
        if (clientId == null) {
            handler.handle(Future.succeededFuture());
            return;
        }
        // get client
        clientSyncService
                .findByClientId(clientId)
                .subscribe(
                        client -> handler.handle(Future.succeededFuture(client)),
                        error -> handler.handle(Future.failedFuture(error)),
                        () -> handler.handle(Future.failedFuture(new InvalidClientException(ClientAuthHandler.GENERIC_ERROR_MESSAGE)))
                );

    });
}
 
Example #21
Source File: ClientBasicAuthProvider.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Client client, HttpServerRequest request, Handler<AsyncResult<Client>> handler) {
    final String authorization = getBasicAuthorization(request);
    if (authorization == null) {
        handler.handle(Future.failedFuture(new InvalidClientException("Invalid client: missing or unsupported authentication method", authenticationHeader())));
        return;
    }
    try {
        // decode the payload
        String decoded = new String(Base64.getDecoder().decode(authorization));
        int colonIdx = decoded.indexOf(":");
        if (colonIdx == -1) {
            throw new IllegalArgumentException();
        }
        String clientId = decoded.substring(0, colonIdx);
        String clientSecret = decoded.substring(colonIdx + 1);
        if (!client.getClientId().equals(clientId) || !client.getClientSecret().equals(clientSecret)) {
            handler.handle(Future.failedFuture(new InvalidClientException(ClientAuthHandler.GENERIC_ERROR_MESSAGE, authenticationHeader())));
            return;
        }
        handler.handle(Future.succeededFuture(client));
    } catch (RuntimeException e) {
        handler.handle(Future.failedFuture(new InvalidClientException("Invalid client: missing or unsupported authentication method", e, authenticationHeader())));
        return;
    }
}
 
Example #22
Source File: ClientPostAuthProviderTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotAuthenticateClient_badClientSecret() 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);
    when(httpServerRequest.getParam(Parameters.CLIENT_ID)).thenReturn("my-client-id");
    when(httpServerRequest.getParam(Parameters.CLIENT_SECRET)).thenReturn("my-other-client-secret");

    CountDownLatch latch = new CountDownLatch(1);
    authProvider.handle(client, httpServerRequest, userAsyncResult -> {
        latch.countDown();
        Assert.assertNotNull(userAsyncResult);
        Assert.assertTrue(userAsyncResult.failed());
        Assert.assertTrue(userAsyncResult.cause() instanceof InvalidClientException);
    });

    assertTrue(latch.await(10, TimeUnit.SECONDS));
}
 
Example #23
Source File: LoginSocialAuthenticationHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private void enhanceSocialIdentityProviders(List<IdentityProvider> identityProviders, HttpServerRequest request, Handler<AsyncResult<List<SocialProviderData>>> resultHandler) {
    Observable.fromIterable(identityProviders)
            .flatMapMaybe(identityProvider -> {
                // get social identity provider type (currently use for display purpose (logo, description, ...)
                String identityProviderType = identityProvider.getType();
                Optional<String> identityProviderSocialType = socialProviders.stream().filter(socialProvider -> identityProviderType.toLowerCase().contains(socialProvider)).findFirst();
                if (identityProviderSocialType.isPresent()) {
                    identityProvider.setType(identityProviderSocialType.get());
                }
                // get social sign in url
                return getAuthorizeUrl(identityProvider.getId(), request)
                        .map(authorizeUrl -> new SocialProviderData(identityProvider, authorizeUrl))
                        .defaultIfEmpty(new SocialProviderData(identityProvider,null));
            })
            .toList()
            .subscribe(socialProviderData -> resultHandler.handle(Future.succeededFuture(socialProviderData)),
                    error -> resultHandler.handle(Future.failedFuture(error)));
}
 
Example #24
Source File: TokenRequestFactory.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
public TokenRequest create(HttpServerRequest request) {
    TokenRequest tokenRequest = new TokenRequest();
    // set technical information
    tokenRequest.setTimestamp(System.currentTimeMillis());
    tokenRequest.setId(RandomString.generate());
    tokenRequest.setTransactionId(RandomString.generate());
    tokenRequest.setUri(request.uri());
    tokenRequest.setOrigin(extractOrigin(request));
    tokenRequest.setContextPath(request.path() != null ? request.path().split("/")[0] : null);
    tokenRequest.setPath(request.path());
    tokenRequest.setHeaders(extractHeaders(request));
    tokenRequest.setParameters(extractRequestParameters(request));
    tokenRequest.setSslSession(request.sslSession());
    tokenRequest.setMethod(request.method() != null ? HttpMethod.valueOf(request.method().name()) : null);
    tokenRequest.setScheme(request.scheme());
    tokenRequest.setRawMethod(request.rawMethod());
    tokenRequest.setVersion(request.version() != null ? HttpVersion.valueOf(request.version().name()) : null);
    tokenRequest.setRemoteAddress(request.remoteAddress() != null ? request.remoteAddress().host() : null);
    tokenRequest.setLocalAddress(request.localAddress() != null ? request.localAddress().host() : null);
    tokenRequest.setHttpResponse(new VertxHttpServerResponse(request.getDelegate(), new VertxHttpServerRequest(request.getDelegate()).metrics()));

    // set OAuth 2.0 information
    tokenRequest.setClientId(request.params().get(Parameters.CLIENT_ID));
    tokenRequest.setGrantType(request.params().get(Parameters.GRANT_TYPE));
    String scope = request.params().get(Parameters.SCOPE);
    tokenRequest.setScopes(scope != null && !scope.isEmpty() ? new HashSet<>(Arrays.asList(scope.split("\\s+"))) : null);
    tokenRequest.setAdditionalParameters(extractAdditionalParameters(request));
    return tokenRequest;
}
 
Example #25
Source File: AuthorizationRequestFactory.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private String extractOrigin(HttpServerRequest request) {
    String basePath = "/";
    try {
        basePath = UriBuilderRequest.resolveProxyRequest(request, "/", null);
    } catch (Exception e) {
        logger.error("Unable to resolve OAuth 2.0 Authorization Request origin uri", e);
    }
    return basePath;
}
 
Example #26
Source File: ClientAssertionAuthProvider.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canHandle(Client client, HttpServerRequest request) {
    if (client != null && (
            ClientAuthenticationMethod.PRIVATE_KEY_JWT.equals(client.getTokenEndpointAuthMethod()) ||
                    ClientAuthenticationMethod.CLIENT_SECRET_JWT.equals(client.getTokenEndpointAuthMethod()))) {
        return true;
    }

    if ((client == null || client.getTokenEndpointAuthMethod() == null || client.getTokenEndpointAuthMethod().isEmpty())
            && getClientAssertion(request) != null && getClientAssertionType(request) != null) {
        return true;
    }
    return false;
}
 
Example #27
Source File: AuthorizationRequestFactory.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
public AuthorizationRequest create(HttpServerRequest request) {
    AuthorizationRequest authorizationRequest = new AuthorizationRequest();
    // set technical information
    authorizationRequest.setTimestamp(System.currentTimeMillis());
    authorizationRequest.setId(RandomString.generate());
    authorizationRequest.setTransactionId(RandomString.generate());
    authorizationRequest.setUri(request.uri());
    authorizationRequest.setOrigin(extractOrigin(request));
    authorizationRequest.setContextPath(request.path() != null ? request.path().split("/")[0] : null);
    authorizationRequest.setPath(request.path());
    authorizationRequest.setHeaders(extractHeaders(request));
    authorizationRequest.setParameters(extractRequestParameters(request));
    authorizationRequest.setSslSession(request.sslSession());
    authorizationRequest.setMethod(request.method() != null ? HttpMethod.valueOf(request.method().name()) : null);
    authorizationRequest.setScheme(request.scheme());
    authorizationRequest.setRawMethod(request.rawMethod());
    authorizationRequest.setVersion(request.version() != null ? HttpVersion.valueOf(request.version().name()) : null);
    authorizationRequest.setRemoteAddress(request.remoteAddress() != null ? request.remoteAddress().host() : null);
    authorizationRequest.setLocalAddress(request.localAddress() != null ? request.localAddress().host() : null);
    authorizationRequest.setHttpResponse(new VertxHttpServerResponse(request.getDelegate(), new VertxHttpServerRequest(request.getDelegate()).metrics()));

    // set OAuth 2.0 information
    authorizationRequest.setClientId(request.params().get(Parameters.CLIENT_ID));
    authorizationRequest.setResponseType(request.params().get(Parameters.RESPONSE_TYPE));
    authorizationRequest.setRedirectUri(request.params().get(Parameters.REDIRECT_URI));
    String scope = request.params().get(Parameters.SCOPE);
    authorizationRequest.setScopes(scope != null && !scope.isEmpty() ? new HashSet<>(Arrays.asList(scope.split("\\s+"))) : null);
    authorizationRequest.setState(request.params().get(Parameters.STATE));
    authorizationRequest.setResponseMode(request.params().get(Parameters.RESPONSE_MODE));
    authorizationRequest.setAdditionalParameters(extractAdditionalParameters(request));

    // set OIDC information
    String prompt = request.params().get(io.gravitee.am.common.oidc.Parameters.PROMPT);
    authorizationRequest.setPrompts(prompt != null ? new HashSet<>(Arrays.asList(prompt.split("\\s+"))) : null);

    return authorizationRequest;
}
 
Example #28
Source File: AuthorizationRequestFactory.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private MultiValueMap<String, String> extractAdditionalParameters(HttpServerRequest request) {
    final Set<String> restrictedParameters = Stream.concat(Parameters.values.stream(),
            io.gravitee.am.common.oidc.Parameters.values.stream()).collect(Collectors.toSet());

    MultiValueMap<String, String> additionalParameters = new LinkedMultiValueMap<>();
    request.params().entries().stream().filter(entry -> !restrictedParameters.contains(entry.getKey())).forEach(entry -> additionalParameters.add(entry.getKey(), entry.getValue()));
    return additionalParameters;
}
 
Example #29
Source File: TokenRequestFactoryTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateRequest_additionalParameters() {
    List<Map.Entry<String, String>> entries = new ArrayList<>();
    entries.add(new Parameter<>(Parameters.CLIENT_ID, "client-id"));
    entries.add(new Parameter<>(Parameters.SCOPE, "scope"));
    entries.add(new Parameter<>(Parameters.GRANT_TYPE, "grant_type"));
    entries.add(new Parameter<>("custom", "additional-parameter"));

    io.vertx.core.MultiMap multiMap = mock(io.vertx.core.MultiMap.class);
    when(multiMap.entries()).thenReturn(entries);

    MultiMap rxMultiMap = mock(MultiMap.class);
    when(rxMultiMap.getDelegate()).thenReturn(multiMap);

    io.vertx.core.http.HttpServerRequest httpServerRequest = mock(io.vertx.core.http.HttpServerRequest.class);
    when(httpServerRequest.method()).thenReturn(HttpMethod.POST);

    HttpServerRequest rxHttpServerRequest = mock(HttpServerRequest.class);
    when(rxHttpServerRequest.params()).thenReturn(rxMultiMap);
    when(rxHttpServerRequest.params().get(Parameters.CLIENT_ID)).thenReturn("client-id");
    when(rxHttpServerRequest.params().get(Parameters.SCOPE)).thenReturn("scope");
    when(rxHttpServerRequest.params().get(Parameters.GRANT_TYPE)).thenReturn("grant_type");
    when(rxHttpServerRequest.params().entries()).thenReturn(entries);
    when(rxHttpServerRequest.getDelegate()).thenReturn(httpServerRequest);

    TokenRequest tokenRequest = tokenRequestFactory.create(rxHttpServerRequest);

    Assert.assertNotNull(tokenRequest);
    Assert.assertEquals("client-id", tokenRequest.getClientId());
    Assert.assertTrue(tokenRequest.getAdditionalParameters().size() == 1 && tokenRequest.getAdditionalParameters().containsKey("custom"));
}
 
Example #30
Source File: UserConsentProcessHandler.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private void saveConsent(HttpServerRequest request, io.gravitee.am.model.User endUser, Client client, List<ScopeApproval> approvals, Handler<AsyncResult<List<ScopeApproval>>> handler) {
    userConsentService.saveConsent(client, approvals, getAuthenticatedUser(request, endUser))
            .subscribe(
                    approvals1 -> handler.handle(Future.succeededFuture(approvals1)),
                    error -> handler.handle(Future.failedFuture(error))
            );
}