use of ch.cyberduck.core.PreferencesUseragentProvider 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;
}
use of ch.cyberduck.core.PreferencesUseragentProvider in project cyberduck by iterate-ch.
the class DriveSession method connect.
@Override
protected Drive connect(final Proxy proxy, final HostKeyCallback callback, final LoginCallback prompt, final CancelCallback cancel) throws HostParserException {
final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
authorizationService = new OAuth2RequestInterceptor(builder.build(ProxyFactory.get().find(host.getProtocol().getOAuthAuthorizationUrl()), this, prompt).build(), host.getProtocol()).withRedirectUri(host.getProtocol().getOAuthRedirectUrl());
configuration.addInterceptorLast(authorizationService);
configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(host, authorizationService, prompt));
configuration.addInterceptorLast(new RateLimitingHttpRequestInterceptor(new DefaultHttpRateLimiter(new HostPreferences(host).getInteger("googledrive.limit.requests.second"))));
this.transport = new ApacheHttpTransport(configuration.build());
final UseragentProvider ua = new PreferencesUseragentProvider();
return new Drive.Builder(transport, new GsonFactory(), new UserAgentHttpRequestInitializer(ua)).setApplicationName(ua.get()).build();
}
use of ch.cyberduck.core.PreferencesUseragentProvider in project cyberduck by iterate-ch.
the class OAuth2AuthorizationService method refresh.
public OAuthTokens refresh(final OAuthTokens tokens) throws BackgroundException {
if (StringUtils.isBlank(tokens.getRefreshToken())) {
log.warn("Missing refresh token");
return tokens;
}
if (log.isDebugEnabled()) {
log.debug(String.format("Refresh expired tokens %s", tokens));
}
try {
final TokenResponse response = new RefreshTokenRequest(transport, json, new GenericUrl(tokenServerUrl), tokens.getRefreshToken()).setRequestInitializer(new UserAgentHttpRequestInitializer(new PreferencesUseragentProvider())).setClientAuthentication(new ClientParametersAuthentication(clientid, clientsecret)).executeUnparsed().parseAs(PermissiveTokenResponse.class).toTokenResponse();
final long expiryInMilliseconds = System.currentTimeMillis() + response.getExpiresInSeconds() * 1000;
if (StringUtils.isBlank(response.getRefreshToken())) {
return new OAuthTokens(response.getAccessToken(), tokens.getRefreshToken(), expiryInMilliseconds);
}
return new OAuthTokens(response.getAccessToken(), response.getRefreshToken(), expiryInMilliseconds);
} catch (TokenResponseException e) {
throw new OAuthExceptionMappingService().map(e);
} catch (HttpResponseException e) {
throw new DefaultHttpResponseExceptionMappingService().map(new org.apache.http.client.HttpResponseException(e.getStatusCode(), e.getStatusMessage()));
} catch (IOException e) {
throw new DefaultIOExceptionMappingService().map(e);
}
}
use of ch.cyberduck.core.PreferencesUseragentProvider in project cyberduck by iterate-ch.
the class OAuth2AuthorizationService method authorizeWithCode.
private TokenResponse authorizeWithCode(final Host bookmark, final LoginCallback prompt, final CancelCallback cancel, final Credentials credentials) throws BackgroundException {
if (PreferencesFactory.get().getBoolean("oauth.browser.open.warn")) {
prompt.warn(bookmark, LocaleFactory.localizedString("Provide additional login credentials", "Credentials"), new StringAppender().append(LocaleFactory.localizedString("Open web browser to authenticate and obtain an authorization code", "Credentials")).append(LocaleFactory.localizedString("Please contact your web hosting service provider for assistance", "Support")).toString(), LocaleFactory.localizedString("Continue", "Credentials"), LocaleFactory.localizedString("Cancel"), "oauth.browser.open.warn");
}
// Start OAuth2 flow within browser
final AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(method, transport, json, new GenericUrl(tokenServerUrl), new ClientParametersAuthentication(clientid, clientsecret), clientid, authorizationServerUrl).setScopes(scopes).setRequestInitializer(new UserAgentHttpRequestInitializer(new PreferencesUseragentProvider())).build();
final AuthorizationCodeRequestUrl authorizationCodeRequestUrl = flow.newAuthorizationUrl();
authorizationCodeRequestUrl.setRedirectUri(redirectUri);
final String state = new AlphanumericRandomStringService().random();
authorizationCodeRequestUrl.setState(state);
for (Map.Entry<String, String> values : additionalParameters.entrySet()) {
authorizationCodeRequestUrl.set(values.getKey(), values.getValue());
}
// Direct the user to an authorization page to grant access to their protected data.
final String url = authorizationCodeRequestUrl.build();
if (log.isDebugEnabled()) {
log.debug(String.format("Open browser with URL %s", url));
}
if (!browser.open(url)) {
log.warn(String.format("Failed to launch web browser for %s", url));
}
final AtomicReference<String> authenticationCode = new AtomicReference<>();
if (StringUtils.contains(redirectUri, CYBERDUCK_REDIRECT_URI)) {
final CountDownLatch signal = new CountDownLatch(1);
final OAuth2TokenListenerRegistry registry = OAuth2TokenListenerRegistry.get();
registry.register(state, new OAuth2TokenListener() {
@Override
public void callback(final String code) {
if (log.isInfoEnabled()) {
log.info(String.format("Callback with code %s", code));
}
if (!StringUtils.isBlank(code)) {
credentials.setSaved(PreferencesFactory.get().getBoolean("connection.login.keychain"));
authenticationCode.set(code);
}
signal.countDown();
}
});
prompt.await(signal, bookmark, LocaleFactory.localizedString("Login", "Login"), LocaleFactory.localizedString("Open web browser to authenticate and obtain an authorization code", "Credentials"));
if (StringUtils.isBlank(authenticationCode.get())) {
throw new LoginCanceledException();
}
} else {
final Credentials input = prompt.prompt(bookmark, LocaleFactory.localizedString("Login", "Login"), LocaleFactory.localizedString("Paste the authentication code from your web browser", "Credentials"), new LoginOptions(bookmark.getProtocol()).keychain(true).user(false).oauth(true).passwordPlaceholder(LocaleFactory.localizedString("Authentication Code", "Credentials")));
credentials.setSaved(input.isSaved());
authenticationCode.set(input.getPassword());
}
try {
if (StringUtils.isBlank(authenticationCode.get())) {
throw new LoginCanceledException();
}
if (log.isDebugEnabled()) {
log.debug(String.format("Request tokens for authentication code %s", authenticationCode.get()));
}
// Swap the given authorization token for access/refresh tokens
return flow.newTokenRequest(authenticationCode.get()).setRedirectUri(redirectUri).setScopes(scopes.isEmpty() ? null : scopes).executeUnparsed().parseAs(PermissiveTokenResponse.class).toTokenResponse();
} catch (TokenResponseException e) {
throw new OAuthExceptionMappingService().map(e);
} catch (HttpResponseException e) {
throw new DefaultHttpResponseExceptionMappingService().map(new org.apache.http.client.HttpResponseException(e.getStatusCode(), e.getStatusMessage()));
} catch (IOException e) {
throw new DefaultIOExceptionMappingService().map(e);
}
}
use of ch.cyberduck.core.PreferencesUseragentProvider in project cyberduck by iterate-ch.
the class GoogleStorageSession method connect.
@Override
protected Storage connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt, final CancelCallback cancel) {
final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
authorizationService = new OAuth2RequestInterceptor(builder.build(ProxyFactory.get().find(host.getProtocol().getOAuthAuthorizationUrl()), this, prompt).build(), host.getProtocol()).withRedirectUri(host.getProtocol().getOAuthRedirectUrl());
configuration.addInterceptorLast(authorizationService);
configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(host, authorizationService, prompt));
this.transport = new ApacheHttpTransport(configuration.build());
final UseragentProvider ua = new PreferencesUseragentProvider();
return new Storage.Builder(transport, new GsonFactory(), new UserAgentHttpRequestInitializer(ua)).setApplicationName(ua.get()).build();
}
Aggregations