Search in sources :

Example 66 with Credentials

use of okhttp3.Credentials in project ETSMobile-Android2 by ApplETS.

the class ETSMobileAuthenticator method getAuthToken.

@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException {
    // Extract the username and password from the Account Manager, and ask
    // the server for an appropriate AuthToken.
    final AccountManager am = AccountManager.get(mContext);
    String authToken = am.peekAuthToken(account, authTokenType);
    SecurePreferences securePreferences = new SecurePreferences(mContext);
    Date expirationDate = Utility.getDate(securePreferences, Constants.EXP_DATE_COOKIE, new Date());
    Date now = new Date();
    // Lets give another try to authenticate the user
    if (TextUtils.isEmpty(authToken) || expirationDate.before(now)) {
        final String password = am.getPassword(account);
        final String username = account.name;
        if (password != null) {
            OkHttpClient client = TLSUtilities.createETSOkHttpClient(mContext);
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "{\n  \"Username\": \"" + username + "\",\n  \"Password\": \"" + password + "\"\n}");
            Request request = new Request.Builder().url(mContext.getString(R.string.portail_api_authentification_url)).post(body).addHeader("content-type", "application/json").addHeader("cache-control", "no-cache").build();
            Response httpResponse = null;
            try {
                httpResponse = client.newCall(request).execute();
                if (httpResponse.code() == 200) {
                    List<String> cookies = httpResponse.headers().values("Set-Cookie");
                    for (String cookie : cookies) {
                        if (cookie.contains(Constants.MONETS_COOKIE_NAME)) {
                            authToken = cookie;
                            break;
                        }
                    }
                    Utility.saveCookieExpirationDate(authToken, securePreferences);
                    JSONObject jsonResponse = new JSONObject(httpResponse.body().string());
                    int typeUsagerId = jsonResponse.getInt("TypeUsagerId");
                    String domaine = jsonResponse.getString("Domaine");
                    securePreferences.edit().putInt(Constants.TYPE_USAGER_ID, typeUsagerId).commit();
                    securePreferences.edit().putString(Constants.DOMAINE, domaine).commit();
                    ApplicationManager.domaine = domaine;
                    ApplicationManager.typeUsagerId = typeUsagerId;
                } else {
                    Log.e("Erreur Portail", httpResponse.toString());
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    // If we get an authToken - we return it
    if (!TextUtils.isEmpty(authToken)) {
        final Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
        result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
        result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
        return result;
    } else {
        final Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
        result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
        result.putString(AccountManager.KEY_AUTHTOKEN, null);
        return result;
    }
// If we get here, then we couldn't access the user's password - so we
// need to re-prompt them for their credentials. We do that by creating
// an intent to display our AuthenticatorActivity.
/*
        final Intent intent = new Intent(mContext, LoginActivity.class);
        intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
        intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, account.type);
        intent.putExtra(Constants.KEY_AUTH_TYPE, authTokenType);
        final Bundle bundle = new Bundle();
        bundle.putParcelable(AccountManager.KEY_INTENT, intent);
        return bundle;
        */
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Bundle(android.os.Bundle) Request(okhttp3.Request) JSONException(org.json.JSONException) IOException(java.io.IOException) Date(java.util.Date) AccountAuthenticatorResponse(android.accounts.AccountAuthenticatorResponse) Response(okhttp3.Response) JSONObject(org.json.JSONObject) MediaType(okhttp3.MediaType) AccountManager(android.accounts.AccountManager) RequestBody(okhttp3.RequestBody)

Example 67 with Credentials

use of okhttp3.Credentials in project collect by opendatakit.

the class OkHttpConnection method uploadSubmissionAndFiles.

@NonNull
@Override
public HttpPostResult uploadSubmissionAndFiles(@NonNull File submissionFile, @NonNull List<File> fileList, @NonNull URI uri, @Nullable HttpCredentialsInterface credentials, @NonNull long contentLength) throws Exception {
    HttpPostResult postResult = null;
    boolean first = true;
    int fileIndex = 0;
    int lastFileIndex;
    while (fileIndex < fileList.size() || first) {
        lastFileIndex = fileIndex;
        first = false;
        long byteCount = 0L;
        RequestBody requestBody = RequestBody.create(MediaType.parse(HTTP_CONTENT_TYPE_TEXT_XML), submissionFile);
        MultipartBody.Builder multipartBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM).addPart(MultipartBody.Part.createFormData("xml_submission_file", submissionFile.getName(), requestBody));
        Timber.i("added xml_submission_file: %s", submissionFile.getName());
        byteCount += submissionFile.length();
        for (; fileIndex < fileList.size(); fileIndex++) {
            File file = fileList.get(fileIndex);
            String contentType = fileToContentTypeMapper.map(file.getName());
            RequestBody fileRequestBody = RequestBody.create(MediaType.parse(contentType), file);
            multipartBuilder.addPart(MultipartBody.Part.createFormData(file.getName(), file.getName(), fileRequestBody));
            byteCount += file.length();
            Timber.i("added file of type '%s' %s", contentType, file.getName());
            // we've added at least one attachment to the request...
            if (fileIndex + 1 < fileList.size()) {
                if ((fileIndex - lastFileIndex + 1 > 100) || (byteCount + fileList.get(fileIndex + 1).length() > contentLength)) {
                    // the next file would exceed the 10MB threshold...
                    Timber.i("Extremely long post is being split into multiple posts");
                    multipartBuilder.addPart(MultipartBody.Part.createFormData("*isIncomplete*", "yes"));
                    // advance over the last attachment added...
                    ++fileIndex;
                    break;
                }
            }
        }
        MultipartBody multipartBody = multipartBuilder.build();
        postResult = executePostRequest(uri, credentials, multipartBody);
        if (postResult.getResponseCode() != HttpURLConnection.HTTP_CREATED && postResult.getResponseCode() != HttpURLConnection.HTTP_ACCEPTED) {
            return postResult;
        }
    }
    return postResult;
}
Also used : MultipartBody(okhttp3.MultipartBody) HttpPostResult(org.odk.collect.android.openrosa.HttpPostResult) File(java.io.File) RequestBody(okhttp3.RequestBody) NonNull(androidx.annotation.NonNull)

Example 68 with Credentials

use of okhttp3.Credentials in project collect by opendatakit.

the class OkHttpConnection method executeGetRequest.

@NonNull
@Override
public HttpGetResult executeGetRequest(@NonNull URI uri, @Nullable String contentType, @Nullable HttpCredentialsInterface credentials) throws Exception {
    OpenRosaServerClient httpClient = clientFactory.get(uri.getScheme(), userAgent, credentials);
    Request request = new Request.Builder().url(uri.toURL()).get().build();
    Response response = httpClient.makeRequest(request, new Date());
    int statusCode = response.code();
    if (statusCode != HttpURLConnection.HTTP_OK) {
        discardEntityBytes(response);
        Timber.i("Error: %s (%s at %s", response.message(), String.valueOf(statusCode), uri.toString());
        return new HttpGetResult(null, new HashMap<String, String>(), "", statusCode);
    }
    ResponseBody body = response.body();
    if (body == null) {
        throw new Exception("No entity body returned from: " + uri.toString());
    }
    if (contentType != null && contentType.length() > 0) {
        MediaType type = body.contentType();
        if (type != null && !type.toString().toLowerCase(Locale.ENGLISH).contains(contentType)) {
            discardEntityBytes(response);
            String error = "ContentType: " + type.toString() + " returned from: " + uri.toString() + " is not " + contentType + ".  This is often caused by a network proxy.  Do you need " + "to login to your network?";
            throw new Exception(error);
        }
    }
    InputStream downloadStream = body.byteStream();
    String hash = "";
    if (HTTP_CONTENT_TYPE_TEXT_XML.equals(contentType)) {
        byte[] bytes = IOUtils.toByteArray(downloadStream);
        downloadStream = new ByteArrayInputStream(bytes);
        hash = Md5.getMd5Hash(new ByteArrayInputStream(bytes));
    }
    Map<String, String> responseHeaders = new HashMap<>();
    Headers headers = response.headers();
    for (int i = 0; i < headers.size(); i++) {
        responseHeaders.put(headers.name(i), headers.value(i));
    }
    return new HttpGetResult(downloadStream, responseHeaders, hash, statusCode);
}
Also used : HashMap(java.util.HashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) CaseInsensitiveHeaders(org.odk.collect.android.openrosa.CaseInsensitiveHeaders) Headers(okhttp3.Headers) CaseInsensitiveEmptyHeaders(org.odk.collect.android.openrosa.CaseInsensitiveEmptyHeaders) Request(okhttp3.Request) Date(java.util.Date) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) OpenRosaServerClient(org.odk.collect.android.openrosa.OpenRosaServerClient) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpGetResult(org.odk.collect.android.openrosa.HttpGetResult) MediaType(okhttp3.MediaType) NonNull(androidx.annotation.NonNull)

Example 69 with Credentials

use of okhttp3.Credentials in project collect by opendatakit.

the class OkHttpOpenRosaServerClientProvider method createNewClient.

@NonNull
private OkHttpOpenRosaServerClient createNewClient(String scheme, String userAgent, @Nullable HttpCredentialsInterface credentials) {
    OkHttpClient.Builder builder = baseClient.newBuilder().connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS).writeTimeout(WRITE_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS).readTimeout(READ_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS).followRedirects(true);
    // 7.0 and 7.1 (API 24/25) use network_security_config to get support.
    if (Build.VERSION.SDK_INT <= 23) {
        try {
            addTrustForLetsEncryptRoot(builder);
        } catch (CertificateException e) {
            Timber.w(e, "Failure attempting to add Let's Encrypt root");
        }
    }
    if (credentials != null) {
        Credentials cred = new Credentials(credentials.getUsername(), credentials.getPassword());
        DispatchingAuthenticator.Builder daBuilder = new DispatchingAuthenticator.Builder();
        daBuilder.with("digest", new DigestAuthenticator(cred));
        if (scheme.equalsIgnoreCase("https")) {
            daBuilder.with("basic", new BasicAuthenticator(cred));
        }
        DispatchingAuthenticator authenticator = daBuilder.build();
        ConcurrentHashMap<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>();
        builder.authenticator(new CachingAuthenticatorDecorator(authenticator, authCache)).addInterceptor(new AuthenticationCacheInterceptor(authCache)).build();
    }
    return new OkHttpOpenRosaServerClient(builder.build(), userAgent);
}
Also used : OkHttpClient(okhttp3.OkHttpClient) CachingAuthenticator(com.burgstaller.okhttp.digest.CachingAuthenticator) CachingAuthenticatorDecorator(com.burgstaller.okhttp.CachingAuthenticatorDecorator) CertificateException(java.security.cert.CertificateException) DispatchingAuthenticator(com.burgstaller.okhttp.DispatchingAuthenticator) BasicAuthenticator(com.burgstaller.okhttp.basic.BasicAuthenticator) DigestAuthenticator(com.burgstaller.okhttp.digest.DigestAuthenticator) AuthenticationCacheInterceptor(com.burgstaller.okhttp.AuthenticationCacheInterceptor) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Credentials(com.burgstaller.okhttp.digest.Credentials) NonNull(androidx.annotation.NonNull)

Example 70 with Credentials

use of okhttp3.Credentials in project keepass2android by PhilippC.

the class WebDavStorage method getClient.

private OkHttpClient getClient(ConnectionInfo ci) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    final Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>();
    com.burgstaller.okhttp.digest.Credentials credentials = new com.burgstaller.okhttp.digest.Credentials(ci.username, ci.password);
    final BasicAuthenticator basicAuthenticator = new BasicAuthenticator(credentials);
    final DigestAuthenticator digestAuthenticator = new DigestAuthenticator(credentials);
    // note that all auth schemes should be registered as lowercase!
    DispatchingAuthenticator authenticator = new DispatchingAuthenticator.Builder().with("digest", digestAuthenticator).with("basic", basicAuthenticator).build();
    builder = builder.authenticator(new CachingAuthenticatorDecorator(authenticator, authCache)).addInterceptor(new AuthenticationCacheInterceptor(authCache));
    if ((mCertificateErrorHandler != null) && (!mCertificateErrorHandler.alwaysFailOnValidationError())) {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
            throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
        }
        X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
        trustManager = new DecoratedTrustManager(trustManager, mCertificateErrorHandler);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { trustManager }, null);
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        builder = builder.sslSocketFactory(sslSocketFactory, trustManager).hostnameVerifier(new DecoratedHostnameVerifier(OkHostnameVerifier.INSTANCE, mCertificateErrorHandler));
    }
    OkHttpClient client = builder.build();
    return client;
}
Also used : OkHttpClient(okhttp3.OkHttpClient) DispatchingAuthenticator(com.burgstaller.okhttp.DispatchingAuthenticator) BasicAuthenticator(com.burgstaller.okhttp.basic.BasicAuthenticator) AuthenticationCacheInterceptor(com.burgstaller.okhttp.AuthenticationCacheInterceptor) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) CachingAuthenticator(com.burgstaller.okhttp.digest.CachingAuthenticator) CachingAuthenticatorDecorator(com.burgstaller.okhttp.CachingAuthenticatorDecorator) SSLContext(javax.net.ssl.SSLContext) TrustManager(javax.net.ssl.TrustManager) DecoratedTrustManager(keepass2android.javafilestorage.webdav.DecoratedTrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) DecoratedHostnameVerifier(keepass2android.javafilestorage.webdav.DecoratedHostnameVerifier) DecoratedTrustManager(keepass2android.javafilestorage.webdav.DecoratedTrustManager) DigestAuthenticator(com.burgstaller.okhttp.digest.DigestAuthenticator) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory)

Aggregations

Request (okhttp3.Request)39 Response (okhttp3.Response)29 OkHttpClient (okhttp3.OkHttpClient)22 IOException (java.io.IOException)20 Test (org.junit.Test)16 HttpUrl (okhttp3.HttpUrl)10 RequestBody (okhttp3.RequestBody)9 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)9 ResponseBody (okhttp3.ResponseBody)8 NonNull (androidx.annotation.NonNull)7 MockResponse (okhttp3.mockwebserver.MockResponse)7 BasicAuthenticator (com.burgstaller.okhttp.basic.BasicAuthenticator)6 CachingAuthenticator (com.burgstaller.okhttp.digest.CachingAuthenticator)6 Credentials (com.burgstaller.okhttp.digest.Credentials)6 DigestAuthenticator (com.burgstaller.okhttp.digest.DigestAuthenticator)6 Observable (rx.Observable)6 AuthenticationCacheInterceptor (com.burgstaller.okhttp.AuthenticationCacheInterceptor)5 CachingAuthenticatorDecorator (com.burgstaller.okhttp.CachingAuthenticatorDecorator)5 PokemonGo (com.pokegoapi.api.PokemonGo)5 PtcCredentialProvider (com.pokegoapi.auth.PtcCredentialProvider)5