Search in sources :

Example 1 with OAuth2ErrorResponseInterceptor

use of ch.cyberduck.core.oauth.OAuth2ErrorResponseInterceptor in project cyberduck by iterate-ch.

the class BoxSession method connect.

@Override
public CloseableHttpClient connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt, final CancelCallback cancel) {
    final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
    authorizationService = new OAuth2RequestInterceptor(configuration.build(), host.getProtocol()).withRedirectUri(host.getProtocol().getOAuthRedirectUrl());
    configuration.addInterceptorLast(authorizationService);
    configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(host, authorizationService, prompt));
    return configuration.build();
}
Also used : OAuth2RequestInterceptor(ch.cyberduck.core.oauth.OAuth2RequestInterceptor) OAuth2ErrorResponseInterceptor(ch.cyberduck.core.oauth.OAuth2ErrorResponseInterceptor) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder)

Example 2 with OAuth2ErrorResponseInterceptor

use of ch.cyberduck.core.oauth.OAuth2ErrorResponseInterceptor in project cyberduck by iterate-ch.

the class SDSSession method connect.

@Override
protected SDSApiClient connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
    final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
    if (preferences.getBoolean("sds.oauth.migrate.enable")) {
        if (host.getProtocol().isDeprecated()) {
            final Credentials credentials = host.getCredentials();
            if (!host.getCredentials().validate(host.getProtocol(), new LoginOptions(host.getProtocol()))) {
                log.warn(String.format("Skip migration with missing credentials for %s", host));
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Attempt migration to OAuth flow for %s", host));
                }
                try {
                    // Search for installed connection profile using OAuth authorization method
                    for (Protocol oauth : ProtocolFactory.get().find(new OAuthFinderPredicate(host.getProtocol().getIdentifier()))) {
                        // Run password flow to attempt to migrate to OAuth
                        final TokenResponse response = new PasswordTokenRequest(new ApacheHttpTransport(builder.build(proxy, this, prompt).build()), new GsonFactory(), new GenericUrl(Scheme.isURL(oauth.getOAuthTokenUrl()) ? oauth.getOAuthTokenUrl() : new HostUrlProvider().withUsername(false).withPath(true).get(oauth.getScheme(), host.getPort(), null, host.getHostname(), oauth.getOAuthTokenUrl())), host.getCredentials().getUsername(), host.getCredentials().getPassword()).setClientAuthentication(new BasicAuthentication(oauth.getOAuthClientId(), oauth.getOAuthClientSecret())).setRequestInitializer(new UserAgentHttpRequestInitializer(new PreferencesUseragentProvider())).execute();
                        final long expiryInMilliseconds = System.currentTimeMillis() + response.getExpiresInSeconds() * 1000;
                        credentials.setOauth(new OAuthTokens(response.getAccessToken(), response.getRefreshToken(), expiryInMilliseconds));
                        credentials.setSaved(true);
                        log.warn(String.format("Switch bookmark %s to protocol %s", host, oauth));
                        host.setProtocol(oauth);
                        break;
                    }
                } catch (IOException e) {
                    log.warn(String.format("Failure %s running password flow to migrate to OAuth", e));
                }
            }
        }
    }
    switch(SDSProtocol.Authorization.valueOf(host.getProtocol().getAuthorization())) {
        case oauth:
        case password:
            authorizationService = new OAuth2RequestInterceptor(builder.build(proxy, this, prompt).addInterceptorLast(new HttpRequestInterceptor() {

                @Override
                public void process(final HttpRequest request, final HttpContext context) {
                    if (request instanceof HttpRequestWrapper) {
                        final HttpRequestWrapper wrapper = (HttpRequestWrapper) request;
                        if (null != wrapper.getTarget()) {
                            if (StringUtils.equals(wrapper.getTarget().getHostName(), host.getHostname())) {
                                request.addHeader(HttpHeaders.AUTHORIZATION, String.format("Basic %s", Base64.encodeToString(String.format("%s:%s", host.getProtocol().getOAuthClientId(), host.getProtocol().getOAuthClientSecret()).getBytes(StandardCharsets.UTF_8), false)));
                            }
                        }
                    }
                }
            }).build(), host) {

                @Override
                public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
                    if (request instanceof HttpRequestWrapper) {
                        final HttpRequestWrapper wrapper = (HttpRequestWrapper) request;
                        if (null != wrapper.getTarget()) {
                            if (StringUtils.equals(wrapper.getTarget().getHostName(), host.getHostname())) {
                                super.process(request, context);
                            }
                        }
                    }
                }
            }.withRedirectUri(CYBERDUCK_REDIRECT_URI.equals(host.getProtocol().getOAuthRedirectUrl()) ? host.getProtocol().getOAuthRedirectUrl() : Scheme.isURL(host.getProtocol().getOAuthRedirectUrl()) ? host.getProtocol().getOAuthRedirectUrl() : new HostUrlProvider().withUsername(false).withPath(true).get(host.getProtocol().getScheme(), host.getPort(), null, host.getHostname(), host.getProtocol().getOAuthRedirectUrl()));
            try {
                authorizationService.withParameter("user_agent_info", Base64.encodeToString(InetAddress.getLocalHost().getHostName().getBytes(StandardCharsets.UTF_8), false));
            } catch (UnknownHostException e) {
                throw new DefaultIOExceptionMappingService().map(e);
            }
            configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(host, authorizationService, prompt));
            configuration.addInterceptorLast(authorizationService);
            configuration.addInterceptorLast(new HttpRequestInterceptor() {

                @Override
                public void process(final HttpRequest request, final HttpContext context) {
                    request.removeHeaders(SDSSession.SDS_AUTH_TOKEN_HEADER);
                }
            });
            break;
        default:
            retryHandler = new SDSErrorResponseInterceptor(this, nodeid);
            configuration.setServiceUnavailableRetryStrategy(retryHandler);
            configuration.addInterceptorLast(retryHandler);
            break;
    }
    final CloseableHttpClient apache = configuration.build();
    final SDSApiClient client = new SDSApiClient(apache);
    client.setBasePath(new HostUrlProvider().withUsername(false).withPath(true).get(host.getProtocol().getScheme(), host.getPort(), null, host.getHostname(), host.getProtocol().getContext()));
    client.setHttpClient(ClientBuilder.newClient(new ClientConfig().register(new InputStreamProvider()).register(MultiPartFeature.class).register(new JSON()).register(JacksonFeature.class).connectorProvider(new HttpComponentsProvider(apache))));
    final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000;
    client.setConnectTimeout(timeout);
    client.setReadTimeout(timeout);
    client.setUserAgent(new PreferencesUseragentProvider().get());
    return client;
}
Also used : UserAgentHttpRequestInitializer(ch.cyberduck.core.http.UserAgentHttpRequestInitializer) JSON(ch.cyberduck.core.sds.io.swagger.client.JSON) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) GenericUrl(com.google.api.client.http.GenericUrl) JacksonFeature(org.glassfish.jersey.jackson.JacksonFeature) OAuth2RequestInterceptor(ch.cyberduck.core.oauth.OAuth2RequestInterceptor) HttpRequestWrapper(org.apache.http.client.methods.HttpRequestWrapper) ClientConfig(org.glassfish.jersey.client.ClientConfig) HttpRequest(org.apache.http.HttpRequest) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) GsonFactory(com.google.api.client.json.gson.GsonFactory) UnknownHostException(java.net.UnknownHostException) InputStreamProvider(org.glassfish.jersey.message.internal.InputStreamProvider) HttpContext(org.apache.http.protocol.HttpContext) OAuth2ErrorResponseInterceptor(ch.cyberduck.core.oauth.OAuth2ErrorResponseInterceptor) IOException(java.io.IOException) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) MultiPartFeature(org.glassfish.jersey.media.multipart.MultiPartFeature) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) BasicAuthentication(com.google.api.client.http.BasicAuthentication) PasswordTokenRequest(com.google.api.client.auth.oauth2.PasswordTokenRequest) ApacheHttpTransport(com.google.api.client.http.apache.v2.ApacheHttpTransport) HttpComponentsProvider(ch.cyberduck.core.jersey.HttpComponentsProvider)

Example 3 with OAuth2ErrorResponseInterceptor

use of ch.cyberduck.core.oauth.OAuth2ErrorResponseInterceptor in project cyberduck by iterate-ch.

the class EueSession method connect.

@Override
protected CloseableHttpClient connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
    final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
    authorizationService = new OAuth2RequestInterceptor(builder.build(proxy, this, prompt).addInterceptorLast(new HttpRequestInterceptor() {

        @Override
        public void process(final HttpRequest request, final HttpContext context) {
            request.addHeader(HttpHeaders.AUTHORIZATION, String.format("Basic %s", Base64.encodeToString(String.format("%s:%s", host.getProtocol().getOAuthClientId(), host.getProtocol().getOAuthClientSecret()).getBytes(StandardCharsets.UTF_8), false)));
        }
    }).build(), host).withRedirectUri(host.getProtocol().getOAuthRedirectUrl());
    configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(host, authorizationService, prompt));
    configuration.addInterceptorLast(authorizationService);
    configuration.addInterceptorLast(new HttpRequestInterceptor() {

        @Override
        public void process(final HttpRequest request, final HttpContext context) {
            final String identifier = new HostPreferences(host).getProperty("apikey");
            if (StringUtils.isNotBlank(identifier)) {
                request.addHeader(new BasicHeader("X-UI-API-KEY", identifier));
            }
        }
    });
    configuration.addInterceptorLast(new HttpRequestInterceptor() {

        @Override
        public void process(final HttpRequest request, final HttpContext context) {
            final String identifier = new HostPreferences(host).getProperty("app");
            if (StringUtils.isNotBlank(identifier)) {
                final String app = String.format("%s.%s", PreferencesFactory.get().getProperty("application.version"), PreferencesFactory.get().getProperty("application.revision"));
                request.addHeader(new BasicHeader("X-UI-APP", MessageFormat.format(identifier, app)));
                if (StringUtils.isNotBlank(vaultResourceId)) {
                    if (StringUtils.contains(request.getRequestLine().getUri(), vaultResourceId)) {
                        // Overwrite default
                        request.setHeader(new BasicHeader("X-UI-APP", MessageFormat.format(StringUtils.replace(identifier, "/", ".tresor/"), app)));
                    }
                }
            }
        }
    });
    configuration.addInterceptorLast(new HttpResponseInterceptor() {

        @Override
        public void process(final HttpResponse response, final HttpContext context) {
            final Optional<Header> hint = Arrays.asList(response.getAllHeaders()).stream().filter(header -> "X-UI-TRAFFIC-HINT".equalsIgnoreCase(header.getName())).findFirst();
            if (hint.isPresent()) {
                // Any response can contain this header. If this happens, a client should take measures to
                // reduce its request rate. We advise to wait two seconds before sending the next request.
                log.warn(String.format("Retrieved throttle warning %s", hint.get()));
                final BackgroundActionPauser pause = new BackgroundActionPauser(new BackgroundActionPauser.Callback() {

                    @Override
                    public void validate() {
                    }

                    @Override
                    public void progress(final Integer seconds) {
                        log.warn(String.format("Pause for %d seconds because of traffic hint", seconds));
                    }
                }, new HostPreferences(host).getInteger("eue.limit.hint.second"));
                pause.await();
            }
        }
    });
    configuration.addInterceptorLast(new RateLimitingHttpRequestInterceptor(new DefaultHttpRateLimiter(new HostPreferences(host).getInteger("eue.limit.requests.second"))));
    return configuration.build();
}
Also used : HttpRequest(org.apache.http.HttpRequest) Optional(java.util.Optional) HttpContext(org.apache.http.protocol.HttpContext) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpResponse(org.apache.http.HttpResponse) OAuth2ErrorResponseInterceptor(ch.cyberduck.core.oauth.OAuth2ErrorResponseInterceptor) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) HostPreferences(ch.cyberduck.core.preferences.HostPreferences) HostKeyCallback(ch.cyberduck.core.HostKeyCallback) CancelCallback(ch.cyberduck.core.threading.CancelCallback) LoginCallback(ch.cyberduck.core.LoginCallback) OAuth2RequestInterceptor(ch.cyberduck.core.oauth.OAuth2RequestInterceptor) DefaultHttpRateLimiter(ch.cyberduck.core.http.DefaultHttpRateLimiter) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) RateLimitingHttpRequestInterceptor(ch.cyberduck.core.http.RateLimitingHttpRequestInterceptor) HttpResponseInterceptor(org.apache.http.HttpResponseInterceptor) BackgroundActionPauser(ch.cyberduck.core.threading.BackgroundActionPauser) RateLimitingHttpRequestInterceptor(ch.cyberduck.core.http.RateLimitingHttpRequestInterceptor) BasicHeader(org.apache.http.message.BasicHeader)

Example 4 with OAuth2ErrorResponseInterceptor

use of ch.cyberduck.core.oauth.OAuth2ErrorResponseInterceptor in project cyberduck by iterate-ch.

the class StoregateSession method connect.

@Override
protected StoregateApiClient connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt, final CancelCallback cancel) {
    final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
    final PreferencesReader preferences = new HostPreferences(host);
    authorizationService = new OAuth2RequestInterceptor(builder.build(proxy, this, prompt).addInterceptorLast(new HttpRequestInterceptor() {

        @Override
        public void process(final HttpRequest request, final HttpContext context) {
            request.addHeader(HttpHeaders.AUTHORIZATION, String.format("Basic %s", Base64.encodeToString(String.format("%s:%s", host.getProtocol().getOAuthClientId(), host.getProtocol().getOAuthClientSecret()).getBytes(StandardCharsets.UTF_8), false)));
        }
    }).build(), host).withRedirectUri(CYBERDUCK_REDIRECT_URI.equals(host.getProtocol().getOAuthRedirectUrl()) ? host.getProtocol().getOAuthRedirectUrl() : Scheme.isURL(host.getProtocol().getOAuthRedirectUrl()) ? host.getProtocol().getOAuthRedirectUrl() : new HostUrlProvider().withUsername(false).withPath(true).get(host.getProtocol().getScheme(), host.getPort(), null, host.getHostname(), host.getProtocol().getOAuthRedirectUrl())).withParameter("login_hint", preferences.getProperty("storegate.login.hint"));
    // Force login even if browser session already exists
    authorizationService.withParameter("prompt", "login");
    configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(host, authorizationService, prompt));
    configuration.addInterceptorLast(authorizationService);
    final CloseableHttpClient apache = configuration.build();
    final StoregateApiClient client = new StoregateApiClient(apache);
    client.setBasePath(new HostUrlProvider().withUsername(false).withPath(true).get(host.getProtocol().getScheme(), host.getPort(), null, host.getHostname(), host.getProtocol().getContext()));
    client.setHttpClient(ClientBuilder.newClient(new ClientConfig().register(new InputStreamProvider()).register(MultiPartFeature.class).register(new JSON()).register(JacksonFeature.class).connectorProvider(new HttpComponentsProvider(apache))));
    final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000;
    client.setConnectTimeout(timeout);
    client.setReadTimeout(timeout);
    client.setUserAgent(new PreferencesUseragentProvider().get());
    return client;
}
Also used : HttpRequest(org.apache.http.HttpRequest) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HostUrlProvider(ch.cyberduck.core.HostUrlProvider) InputStreamProvider(org.glassfish.jersey.message.internal.InputStreamProvider) HttpContext(org.apache.http.protocol.HttpContext) OAuth2ErrorResponseInterceptor(ch.cyberduck.core.oauth.OAuth2ErrorResponseInterceptor) JSON(ch.cyberduck.core.storegate.io.swagger.client.JSON) PreferencesUseragentProvider(ch.cyberduck.core.PreferencesUseragentProvider) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) PreferencesReader(ch.cyberduck.core.preferences.PreferencesReader) HostPreferences(ch.cyberduck.core.preferences.HostPreferences) JacksonFeature(org.glassfish.jersey.jackson.JacksonFeature) OAuth2RequestInterceptor(ch.cyberduck.core.oauth.OAuth2RequestInterceptor) MultiPartFeature(org.glassfish.jersey.media.multipart.MultiPartFeature) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) ClientConfig(org.glassfish.jersey.client.ClientConfig) HttpComponentsProvider(ch.cyberduck.core.jersey.HttpComponentsProvider)

Example 5 with OAuth2ErrorResponseInterceptor

use of ch.cyberduck.core.oauth.OAuth2ErrorResponseInterceptor in project cyberduck by iterate-ch.

the class DropboxSession method connect.

@Override
protected CustomDbxRawClientV2 connect(final Proxy proxy, final HostKeyCallback callback, final LoginCallback prompt, final CancelCallback cancel) {
    final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
    authorizationService = new OAuth2RequestInterceptor(configuration.build(), host.getProtocol()).withRedirectUri(host.getProtocol().getOAuthRedirectUrl());
    configuration.addInterceptorLast(authorizationService);
    configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(host, authorizationService, prompt));
    final CloseableHttpClient client = configuration.build();
    return new CustomDbxRawClientV2(DbxRequestConfig.newBuilder(useragent.get()).withAutoRetryDisabled().withHttpRequestor(new DropboxCommonsHttpRequestExecutor(client)).build(), DbxHost.DEFAULT, null, null);
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) CustomDbxRawClientV2(com.dropbox.core.v2.CustomDbxRawClientV2) OAuth2RequestInterceptor(ch.cyberduck.core.oauth.OAuth2RequestInterceptor) OAuth2ErrorResponseInterceptor(ch.cyberduck.core.oauth.OAuth2ErrorResponseInterceptor) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder)

Aggregations

OAuth2ErrorResponseInterceptor (ch.cyberduck.core.oauth.OAuth2ErrorResponseInterceptor)9 OAuth2RequestInterceptor (ch.cyberduck.core.oauth.OAuth2RequestInterceptor)9 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)9 HttpRequest (org.apache.http.HttpRequest)4 HttpContext (org.apache.http.protocol.HttpContext)4 PreferencesUseragentProvider (ch.cyberduck.core.PreferencesUseragentProvider)3 UserAgentHttpRequestInitializer (ch.cyberduck.core.http.UserAgentHttpRequestInitializer)3 HostPreferences (ch.cyberduck.core.preferences.HostPreferences)3 ApacheHttpTransport (com.google.api.client.http.apache.v2.ApacheHttpTransport)3 GsonFactory (com.google.api.client.json.gson.GsonFactory)3 HttpRequestInterceptor (org.apache.http.HttpRequestInterceptor)3 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)3 UseragentProvider (ch.cyberduck.core.UseragentProvider)2 DefaultHttpRateLimiter (ch.cyberduck.core.http.DefaultHttpRateLimiter)2 RateLimitingHttpRequestInterceptor (ch.cyberduck.core.http.RateLimitingHttpRequestInterceptor)2 HttpComponentsProvider (ch.cyberduck.core.jersey.HttpComponentsProvider)2 IOException (java.io.IOException)2 ClientConfig (org.glassfish.jersey.client.ClientConfig)2 JacksonFeature (org.glassfish.jersey.jackson.JacksonFeature)2 MultiPartFeature (org.glassfish.jersey.media.multipart.MultiPartFeature)2