Search in sources :

Example 6 with Credentials

use of okhttp3.Credentials in project java-cloudant by cloudant.

the class HttpTest method badCredsDisablesCookie.

/**
 * Test that cookie authentication is stopped if the credentials were bad.
 *
 * @throws Exception
 */
@TestTemplate
public void badCredsDisablesCookie() throws Exception {
    mockWebServer.setDispatcher(new Dispatcher() {

        private int counter = 0;

        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            counter++;
            // Return a 401 for the first _session request, after that return 200 OKs
            if (counter == 1) {
                return new MockResponse().setResponseCode(401);
            } else {
                return new MockResponse().setBody("TEST");
            }
        }
    });
    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer).username("bad").password("worse").build();
    String response = c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
    assertEquals("TEST", response, "The expected response body should be received");
    // There should only be two requests: an initial auth failure followed by an ok response.
    // If the cookie interceptor keeps trying then there will be more _session requests.
    assertEquals(2, mockWebServer.getRequestCount(), "There should be 2 requests");
    assertEquals("/_session", MockWebServerResources.takeRequestWithTimeout(mockWebServer).getPath(), "The " + "first request should have been for a cookie");
    assertEquals("/", MockWebServerResources.takeRequestWithTimeout(mockWebServer).getPath(), "The " + "second request should have been for /");
    response = c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
    assertEquals("TEST", response, "The expected response body should be received");
    // Make another request, the cookie interceptor should not try again so there should only be
    // one more request.
    assertEquals(3, mockWebServer.getRequestCount(), "There should be 3 requests");
    assertEquals("/", MockWebServerResources.takeRequestWithTimeout(mockWebServer).getPath(), "The third request should have been for /");
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) CloudantClient(com.cloudant.client.api.CloudantClient) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Dispatcher(okhttp3.mockwebserver.Dispatcher) TestTemplate(org.junit.jupiter.api.TestTemplate)

Example 7 with Credentials

use of okhttp3.Credentials in project nifi by apache.

the class InvokeHTTP method setAuthenticator.

private void setAuthenticator(OkHttpClient.Builder okHttpClientBuilder, ProcessContext context) {
    final String authUser = trimToEmpty(context.getProperty(PROP_BASIC_AUTH_USERNAME).getValue());
    final String proxyUsername = trimToEmpty(context.getProperty(PROP_PROXY_USER).evaluateAttributeExpressions().getValue());
    // If the username/password properties are set then check if digest auth is being used
    if (!authUser.isEmpty() && "true".equalsIgnoreCase(context.getProperty(PROP_DIGEST_AUTH).getValue())) {
        final String authPass = trimToEmpty(context.getProperty(PROP_BASIC_AUTH_PASSWORD).getValue());
        /*
             * OkHttp doesn't have built-in Digest Auth Support. A ticket for adding it is here[1] but they authors decided instead to rely on a 3rd party lib.
             *
             * [1] https://github.com/square/okhttp/issues/205#issuecomment-154047052
             */
        final Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>();
        com.burgstaller.okhttp.digest.Credentials credentials = new com.burgstaller.okhttp.digest.Credentials(authUser, authPass);
        final DigestAuthenticator digestAuthenticator = new DigestAuthenticator(credentials);
        if (!proxyUsername.isEmpty()) {
            final String proxyPassword = context.getProperty(PROP_PROXY_PASSWORD).evaluateAttributeExpressions().getValue();
            ProxyAuthenticator proxyAuthenticator = new ProxyAuthenticator(proxyUsername, proxyPassword);
            okHttpClientBuilder.proxyAuthenticator(proxyAuthenticator);
        }
        okHttpClientBuilder.interceptors().add(new AuthenticationCacheInterceptor(authCache));
        okHttpClientBuilder.authenticator(new CachingAuthenticatorDecorator(digestAuthenticator, authCache));
    } else {
        // Add proxy authentication only
        if (!proxyUsername.isEmpty()) {
            final String proxyPassword = context.getProperty(PROP_PROXY_PASSWORD).evaluateAttributeExpressions().getValue();
            ProxyAuthenticator proxyAuthenticator = new ProxyAuthenticator(proxyUsername, proxyPassword);
            okHttpClientBuilder.proxyAuthenticator(proxyAuthenticator);
        }
    }
}
Also used : CachingAuthenticator(com.burgstaller.okhttp.digest.CachingAuthenticator) CachingAuthenticatorDecorator(com.burgstaller.okhttp.CachingAuthenticatorDecorator) ProxyAuthenticator(org.apache.nifi.processors.standard.util.ProxyAuthenticator) DigestAuthenticator(com.burgstaller.okhttp.digest.DigestAuthenticator) AuthenticationCacheInterceptor(com.burgstaller.okhttp.AuthenticationCacheInterceptor) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Credentials(okhttp3.Credentials)

Example 8 with Credentials

use of okhttp3.Credentials in project jdk8u_jdk by JetBrains.

the class Krb5Util method getTicketFromSubjectAndTgs.

/**
     * Retrieve the service ticket for serverPrincipal from caller's Subject
     * or from Subject obtained by logging in, or if not found, via the
     * Ticket Granting Service using the TGT obtained from the Subject.
     *
     * Caller must have permission to:
     *    - access and update Subject's private credentials
     *    - create LoginContext
     *    - read the auth.login.defaultCallbackHandler security property
     *
     * NOTE: This method is used by JSSE Kerberos Cipher Suites
     */
public static KerberosTicket getTicketFromSubjectAndTgs(GSSCaller caller, String clientPrincipal, String serverPrincipal, String tgsPrincipal, AccessControlContext acc) throws LoginException, KrbException, IOException {
    // 1. Try to find service ticket in acc subject
    Subject accSubj = Subject.getSubject(acc);
    KerberosTicket ticket = SubjectComber.find(accSubj, serverPrincipal, clientPrincipal, KerberosTicket.class);
    if (ticket != null) {
        // found it
        return ticket;
    }
    Subject loginSubj = null;
    if (!GSSUtil.useSubjectCredsOnly(caller)) {
        // 2. Try to get ticket from login
        try {
            loginSubj = GSSUtil.login(caller, GSSUtil.GSS_KRB5_MECH_OID);
            ticket = SubjectComber.find(loginSubj, serverPrincipal, clientPrincipal, KerberosTicket.class);
            if (ticket != null) {
                // found it
                return ticket;
            }
        } catch (LoginException e) {
        // No login entry to use
        // ignore and continue
        }
    }
    // Service ticket not found in subject or login
    // Try to get TGT to acquire service ticket
    // 3. Try to get TGT from acc subject
    KerberosTicket tgt = SubjectComber.find(accSubj, tgsPrincipal, clientPrincipal, KerberosTicket.class);
    boolean fromAcc;
    if (tgt == null && loginSubj != null) {
        // 4. Try to get TGT from login subject
        tgt = SubjectComber.find(loginSubj, tgsPrincipal, clientPrincipal, KerberosTicket.class);
        fromAcc = false;
    } else {
        fromAcc = true;
    }
    // 5. Try to get service ticket using TGT
    if (tgt != null) {
        Credentials tgtCreds = ticketToCreds(tgt);
        Credentials serviceCreds = Credentials.acquireServiceCreds(serverPrincipal, tgtCreds);
        if (serviceCreds != null) {
            ticket = credsToTicket(serviceCreds);
            // Store service ticket in acc's Subject
            if (fromAcc && accSubj != null && !accSubj.isReadOnly()) {
                accSubj.getPrivateCredentials().add(ticket);
            }
        }
    }
    return ticket;
}
Also used : KerberosTicket(javax.security.auth.kerberos.KerberosTicket) LoginException(javax.security.auth.login.LoginException) Subject(javax.security.auth.Subject) Credentials(sun.security.krb5.Credentials)

Example 9 with Credentials

use of okhttp3.Credentials in project data-transfer-project by google.

the class MicrosoftAuthServiceExtension method initialize.

@Override
public void initialize(ExtensionContext context) {
    mapper = context.getTypeManager().getMapper();
    OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
    okHttpClient = clientBuilder.build();
    AppCredentialStore appCredentialStore = context.getService(AppCredentialStore.class);
    try {
        AppCredentials credentials = appCredentialStore.getAppCredentials("MICROSOFT_KEY", "MICROSOFT_SECRET");
        if (credentials == null) {
            throw new IllegalStateException("Microsoft Graph API credentials not found");
        }
    } catch (IOException e) {
        throw new IllegalStateException("Error retrieving Microsoft Graph API credentials - Were they set?", e);
    }
    importAuthDataGenerators = new HashMap<>();
    exportAuthDataGenerators = new HashMap<>();
    initialized = true;
}
Also used : OkHttpClient(okhttp3.OkHttpClient) AppCredentialStore(org.dataportabilityproject.spi.cloud.storage.AppCredentialStore) AppCredentials(org.dataportabilityproject.types.transfer.auth.AppCredentials) IOException(java.io.IOException)

Example 10 with Credentials

use of okhttp3.Credentials in project android-client by GenesisVision.

the class HttpBasicAuth method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    // If the request already have an authorization (eg. Basic auth), do nothing
    if (request.header("Authorization") == null) {
        String credentials = Credentials.basic(username, password);
        request = request.newBuilder().addHeader("Authorization", credentials).build();
    }
    return chain.proceed(request);
}
Also used : Request(okhttp3.Request)

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