use of com.google.api.client.http.BasicAuthentication 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;
}
use of com.google.api.client.http.BasicAuthentication in project cyberduck by iterate-ch.
the class FreenetAuthenticatedUrlProvider method toUrl.
@Override
public DescriptiveUrl toUrl(final Host bookmark) {
try {
// Run password flow
final TokenResponse response;
try {
final Host target = new Host(new DAVSSLProtocol(), "oauth.freenet.de");
final X509TrustManager trust = new KeychainX509TrustManager(new DisabledCertificateTrustCallback(), new DefaultTrustManagerHostnameCallback(target), CertificateStoreFactory.get());
final X509KeyManager key = new KeychainX509KeyManager(new DisabledCertificateIdentityCallback(), target, CertificateStoreFactory.get());
final CloseableHttpClient client = new HttpConnectionPoolBuilder(target, new ThreadLocalHostnameDelegatingTrustManager(trust, target.getHostname()), key, ProxyFactory.get()).build(ProxyFactory.get().find(new ProxyHostUrlProvider().get(target)), new DisabledTranscriptListener(), new DisabledLoginCallback()).setUserAgent(new FreenetUserAgentProvider().get()).build();
final String username = bookmark.getCredentials().getUsername();
final String password;
if (StringUtils.isBlank(bookmark.getCredentials().getPassword())) {
password = PasswordStoreFactory.get().findLoginPassword(bookmark);
} else {
password = bookmark.getCredentials().getPassword();
}
response = new PasswordTokenRequest(new ApacheHttpTransport(client), new GsonFactory(), new GenericUrl("https://oauth.freenet.de/oauth/token"), username, password).setClientAuthentication(new BasicAuthentication("desktop_client", "6LIGIHuOSkznLomu5xw0EPPBJOXb2jLp")).setRequestInitializer(new UserAgentHttpRequestInitializer(new FreenetUserAgentProvider())).set("world", new HostPreferences(bookmark).getProperty("world")).set("webLogin", Boolean.TRUE).execute();
final FreenetTemporaryLoginResponse login = this.getLoginSession(client, response.getAccessToken());
return new DescriptiveUrl(URI.create(login.urls.login), DescriptiveUrl.Type.authenticated);
} catch (IOException e) {
throw new HttpExceptionMappingService().map(e);
}
} catch (BackgroundException e) {
log.warn(String.format("Failure %s retrieving authenticated URL for %s", e, bookmark));
return DescriptiveUrl.EMPTY;
}
}
use of com.google.api.client.http.BasicAuthentication in project urlaubsverwaltung by synyx.
the class GoogleCalendarSyncProvider method createCredentialWithRefreshToken.
private Credential createCredentialWithRefreshToken(HttpTransport transport, JsonFactory jsonFactory, TokenResponse tokenResponse) {
String clientId = settingsService.getSettings().getCalendarSettings().getGoogleCalendarSettings().getClientId();
String clientSecret = settingsService.getSettings().getCalendarSettings().getGoogleCalendarSettings().getClientSecret();
return new Credential.Builder(BearerToken.authorizationHeaderAccessMethod()).setTransport(transport).setJsonFactory(jsonFactory).setTokenServerUrl(new GenericUrl(GOOGLEAPIS_OAUTH2_V4_TOKEN)).setClientAuthentication(new BasicAuthentication(clientId, clientSecret)).build().setFromTokenResponse(tokenResponse);
}
use of com.google.api.client.http.BasicAuthentication in project google-oauth-java-client by googleapis.
the class CredentialTest method subtestConstructor_expired.
private HttpRequest subtestConstructor_expired(Credential.AccessMethod method, final CheckAuth checkAuth) throws Exception {
final Credential credential = new Credential.Builder(method).setTransport(new AccessTokenTransport()).setJsonFactory(JSON_FACTORY).setTokenServerUrl(TOKEN_SERVER_URL).setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET)).build().setAccessToken(ACCESS_TOKEN).setRefreshToken(REFRESH_TOKEN);
class MyTransport extends MockHttpTransport {
boolean resetAccessToken;
@Override
public LowLevelHttpRequest buildRequest(String method, String url) {
return new MockLowLevelHttpRequest(url) {
@Override
public LowLevelHttpResponse execute() {
MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
if (!checkAuth.checkAuth(this)) {
response.setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
if (resetAccessToken) {
credential.setAccessToken(NEW_ACCESS_TOKEN);
}
}
return response;
}
};
}
}
MyTransport transport = new MyTransport();
HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
HttpRequest request = requestFactory.buildDeleteRequest(HttpTesting.SIMPLE_GENERIC_URL);
request.execute();
credential.setAccessToken(ACCESS_TOKEN);
transport.resetAccessToken = true;
request.execute();
return request;
}
use of com.google.api.client.http.BasicAuthentication in project google-oauth-java-client by googleapis.
the class CredentialTest method testRefreshToken_noRefreshToken2.
public void testRefreshToken_noRefreshToken2() throws Exception {
AccessTokenTransport transport = new AccessTokenTransport();
Credential access = new Credential.Builder(BearerToken.queryParameterAccessMethod()).setTransport(transport).setJsonFactory(JSON_FACTORY).setTokenServerUrl(TOKEN_SERVER_URL).setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET)).build().setAccessToken(ACCESS_TOKEN);
assertFalse(access.refreshToken());
assertEquals(ACCESS_TOKEN, access.getAccessToken());
assertNull(access.getRefreshToken());
assertNull(access.getExpirationTimeMilliseconds());
}
Aggregations