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();
}
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();
}
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"));
}
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"));
}
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));
}
Aggregations