Search in sources :

Example 66 with Authenticator

use of okhttp3.Authenticator in project Audient by komamj.

the class AudientRepositoryModule method provideOkHttpClient.

@Singleton
@Provides
OkHttpClient provideOkHttpClient(Cache cache, final SharedPreferences sharedPreferences, final Gson gson) {
    final HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();
    if (BuildConfig.DEBUG) {
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    }
    return new OkHttpClient.Builder().authenticator(new Authenticator() {

        @Nullable
        @Override
        public Request authenticate(Route route, Response response) throws IOException {
            String refershToken = sharedPreferences.getString(Constants.REFRESH_TOKEN, "");
            Retrofit retrofit = new Retrofit.Builder().baseUrl(Constants.AUDIENT_HOST).client(new OkHttpClient.Builder().addInterceptor(logInterceptor).build()).addConverterFactory(GsonConverterFactory.create(gson)).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build();
            AudientApi audientApi = retrofit.create(AudientApi.class);
            audientApi.refreshAccessToken(GRANT_TYPE, refershToken, Constants.CLIENT_ID, Constants.CLIENT_SECRET).subscribeWith(new DisposableSubscriber<Token>() {

                @Override
                public void onNext(Token token) {
                    sharedPreferences.edit().putString(Constants.ACCESS_TOKEN, token.accessToken).commit();
                    sharedPreferences.edit().putString(Constants.REFRESH_TOKEN, token.refreshToken).commit();
                }

                @Override
                public void onError(Throwable t) {
                    LogUtils.e(TAG, "refresh token error :" + t.getMessage());
                    sharedPreferences.edit().putBoolean(Constants.LOGIN_STATUS, false).commit();
                    android.os.Process.killProcess(android.os.Process.myPid());
                }

                @Override
                public void onComplete() {
                }
            });
            return response.request().newBuilder().header("Authorization", "Bearer " + sharedPreferences.getString(Constants.ACCESS_TOKEN, "")).build();
        }
    }).addInterceptor(new TokenInterceptor(sharedPreferences)).addInterceptor(logInterceptor).cache(cache).connectTimeout(15, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS).retryOnConnectionFailure(true).build();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) GsonBuilder(com.google.gson.GsonBuilder) Request(okhttp3.Request) Token(com.xinshang.audient.model.entities.Token) IOException(java.io.IOException) DisposableSubscriber(io.reactivex.subscribers.DisposableSubscriber) Response(okhttp3.Response) Retrofit(retrofit2.Retrofit) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Authenticator(okhttp3.Authenticator) Nullable(android.support.annotation.Nullable) Route(okhttp3.Route) TokenInterceptor(com.xinshang.audient.model.helper.TokenInterceptor) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

Example 67 with Authenticator

use of okhttp3.Authenticator in project okhttp by square.

the class DuplexTest method duplexWithAuthChallenge.

/**
 * Auth requires follow-ups. Unlike redirects, the auth follow-up also has a request body. This
 * test makes a single call with two duplex requests!
 */
@Test
public void duplexWithAuthChallenge() throws Exception {
    enableProtocol(Protocol.HTTP_2);
    String credential = Credentials.basic("jesse", "secret");
    client = client.newBuilder().authenticator(new RecordingOkAuthenticator(credential, null)).build();
    MockDuplexResponseBody mockResponseBody1 = enqueueResponseWithBody(new MockResponse().clearHeaders().setResponseCode(HttpURLConnection.HTTP_UNAUTHORIZED), new MockDuplexResponseBody().sendResponse("please authenticate!\n").requestIOException().exhaustResponse());
    MockDuplexResponseBody mockResponseBody2 = enqueueResponseWithBody(new MockResponse().clearHeaders(), new MockDuplexResponseBody().sendResponse("response body\n").exhaustResponse().receiveRequest("request body\n").exhaustRequest());
    Call call = client.newCall(new Request.Builder().url(server.url("/")).post(new AsyncRequestBody()).build());
    Response response2 = call.execute();
    // First duplex request is detached with violence.
    BufferedSink requestBody1 = ((AsyncRequestBody) call.request().body()).takeSink();
    try {
        requestBody1.writeUtf8("not authenticated\n");
        requestBody1.flush();
        fail();
    } catch (IOException expected) {
        assertThat(expected.getMessage()).isEqualTo("stream was reset: CANCEL");
    }
    mockResponseBody1.awaitSuccess();
    // Second duplex request proceeds normally.
    BufferedSink requestBody2 = ((AsyncRequestBody) call.request().body()).takeSink();
    requestBody2.writeUtf8("request body\n");
    requestBody2.close();
    BufferedSource responseBody2 = response2.body().source();
    assertThat(responseBody2.readUtf8Line()).isEqualTo("response body");
    assertTrue(responseBody2.exhausted());
    mockResponseBody2.awaitSuccess();
    // No more requests attempted!
    ((AsyncRequestBody) call.request().body()).assertNoMoreSinks();
}
Also used : MockResponse(mockwebserver3.MockResponse) MockResponse(mockwebserver3.MockResponse) RecordingOkAuthenticator(okhttp3.internal.RecordingOkAuthenticator) MockDuplexResponseBody(mockwebserver3.internal.duplex.MockDuplexResponseBody) AsyncRequestBody(okhttp3.internal.duplex.AsyncRequestBody) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) BufferedSource(okio.BufferedSource) Test(org.junit.jupiter.api.Test)

Example 68 with Authenticator

use of okhttp3.Authenticator in project edx-app-android by edx.

the class AuthenticationTests method testAuthenticate_notForExpiredAccessToken.

@Test
public void testAuthenticate_notForExpiredAccessToken() throws Exception {
    client = client.newBuilder().authenticator(new OauthRefreshTokenAuthenticator(context)).build();
    Request request = new Request.Builder().url(mockServer.url("/dummy/endpoint/")).header("Authorization", "401_not_caused_by_expired_token").build();
    Response response = client.newCall(request).execute();
    assertEquals(HttpStatus.UNAUTHORIZED, response.code());
    assertEquals("401_not_caused_by_expired_token", response.request().header("Authorization"));
}
Also used : OauthRefreshTokenAuthenticator(org.edx.mobile.http.authenticator.OauthRefreshTokenAuthenticator) AuthResponse(org.edx.mobile.authentication.AuthResponse) Response(okhttp3.Response) MockResponse(okhttp3.mockwebserver.MockResponse) Request(okhttp3.Request) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Test(org.junit.Test)

Example 69 with Authenticator

use of okhttp3.Authenticator in project edx-app-android by edx.

the class AuthenticationTests method testAuthenticate_forExpiredAccessToken.

@Test
public void testAuthenticate_forExpiredAccessToken() throws Exception {
    // create a client with the authenticator
    client = client.newBuilder().authenticator(new OauthRefreshTokenAuthenticator(context)).build();
    // Build a new dummy request to trigger authenticator
    Request request = new Request.Builder().url(mockServer.url("/dummy/endpoint/")).header("Authorization", "expired_token").build();
    // Make request
    Response response = client.newCall(request).execute();
    assertEquals(HttpStatus.OK, response.code());
    assertEquals("Bearer dummy", response.request().header("Authorization"));
    // Assert the expired token request was sent
    RecordedRequest expiredRequest = mockServer.takeRequest();
    assertEquals("/dummy/endpoint/", expiredRequest.getPath());
    assertEquals("expired_token", expiredRequest.getHeader("Authorization"));
    // Assert the authenticator requests for a new access token using the refresh token
    RecordedRequest refreshTokenRequest = mockServer.takeRequest();
    assertEquals("/oauth2/access_token/", refreshTokenRequest.getPath());
    String actual_body = refreshTokenRequest.getBody().readUtf8();
    assertTrue(actual_body.contains("grant_type=refresh_token"));
    assertTrue(actual_body.contains("refresh_token=dummy_refresh_token"));
    // Assert that the original request was made again with the new token.
    RecordedRequest refreshedRequest = mockServer.takeRequest();
    assertEquals("/dummy/endpoint/", refreshedRequest.getPath());
    assertEquals("Bearer dummy", refreshedRequest.getHeader("Authorization"));
}
Also used : OauthRefreshTokenAuthenticator(org.edx.mobile.http.authenticator.OauthRefreshTokenAuthenticator) AuthResponse(org.edx.mobile.authentication.AuthResponse) Response(okhttp3.Response) MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Request(okhttp3.Request) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Test(org.junit.Test)

Example 70 with Authenticator

use of okhttp3.Authenticator in project codekvast by crispab.

the class AgentConfigTest method should_create_http_client_without_httpProxy.

@Test
public void should_create_http_client_without_httpProxy() {
    AgentConfig config = AgentConfigFactory.createSampleAgentConfig().toBuilder().httpProxyUsername("proxyUsername").build();
    OkHttpClient httpClient = config.getHttpClient();
    assertThat(httpClient, not(nullValue()));
    assertThat(httpClient.proxy(), nullValue());
    Authenticator authenticator = httpClient.proxyAuthenticator();
    assertThat(authenticator, is(Authenticator.NONE));
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Authenticator(okhttp3.Authenticator) Test(org.junit.jupiter.api.Test)

Aggregations

Test (org.junit.Test)37 Request (okhttp3.Request)27 OkHttpClient (okhttp3.OkHttpClient)26 Response (okhttp3.Response)24 MockResponse (okhttp3.mockwebserver.MockResponse)23 Authenticator (okhttp3.Authenticator)20 IOException (java.io.IOException)15 RecordingOkAuthenticator (okhttp3.internal.RecordingOkAuthenticator)15 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)13 Route (okhttp3.Route)12 BasicAuthenticator (com.burgstaller.okhttp.basic.BasicAuthenticator)9 DigestAuthenticator (com.burgstaller.okhttp.digest.DigestAuthenticator)8 CachingAuthenticator (com.burgstaller.okhttp.digest.CachingAuthenticator)7 InetSocketAddress (java.net.InetSocketAddress)7 RecordingAuthenticator (okhttp3.internal.RecordingAuthenticator)6 Credentials (com.burgstaller.okhttp.digest.Credentials)5 InetAddress (java.net.InetAddress)5 Proxy (java.net.Proxy)5 Interceptor (okhttp3.Interceptor)5 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)5