Search in sources :

Example 41 with Credentials

use of okhttp3.Credentials in project PokeGOAPI-Java by Grover-c13.

the class PtcCredentialProvider method login.

/**
 * Starts a login flow for pokemon.com (PTC) using a username and password,
 * this uses pokemon.com's oauth endpoint and returns a usable AuthInfo without user interaction
 *
 * @param username PTC username
 * @param password PTC password
 * @param attempt the current attempt index
 * @throws LoginFailedException if an exception occurs while attempting to log in
 * @throws InvalidCredentialsException if invalid credentials are used
 */
private void login(String username, String password, int attempt) throws LoginFailedException, InvalidCredentialsException {
    try {
        // TODO: stop creating an okhttp client per request
        Response getResponse;
        try {
            getResponse = client.newCall(new Request.Builder().url(HttpUrl.parse("https://sso.pokemon.com/sso/oauth2.0/authorize").newBuilder().addQueryParameter("client_id", CLIENT_ID).addQueryParameter("redirect_uri", REDIRECT_URI).addQueryParameter("locale", "en").build()).get().build()).execute();
        } catch (IOException e) {
            throw new LoginFailedException("Failed to receive contents from server", e);
        }
        Moshi moshi = new Moshi.Builder().build();
        PtcAuthJson ptcAuth;
        try {
            ptcAuth = moshi.adapter(PtcAuthJson.class).fromJson(getResponse.body().string());
        } catch (IOException e) {
            throw new LoginFailedException("Looks like the servers are down", e);
        }
        Response postResponse;
        try {
            FormBody postForm = new Builder().add("lt", ptcAuth.lt).add("execution", ptcAuth.execution).add("_eventId", "submit").add("username", username).add("password", password).add("locale", "en_US").build();
            HttpUrl loginPostUrl = HttpUrl.parse(LOGIN_URL).newBuilder().addQueryParameter("service", SERVICE_URL).build();
            Request postRequest = new Request.Builder().url(loginPostUrl).post(postForm).build();
            // Need a new client for this to not follow redirects
            postResponse = client.newBuilder().followRedirects(false).followSslRedirects(false).build().newCall(postRequest).execute();
        } catch (IOException e) {
            throw new LoginFailedException("Network failure", e);
        }
        String postBody;
        try {
            postBody = postResponse.body().string();
        } catch (IOException e) {
            throw new LoginFailedException("Response body fetching failed", e);
        }
        List<Cookie> cookies = client.cookieJar().loadForRequest(HttpUrl.parse(LOGIN_URL));
        for (Cookie cookie : cookies) {
            if (cookie.name().startsWith("CASTGC")) {
                this.tokenId = cookie.value();
                expiresTimestamp = time.currentTimeMillis() + 7140000L;
                return;
            }
        }
        if (postBody.length() > 0) {
            try {
                String[] errors = moshi.adapter(PtcAuthError.class).fromJson(postBody).errors;
                if (errors != null && errors.length > 0) {
                    throw new InvalidCredentialsException(errors[0]);
                }
            } catch (IOException e) {
                throw new LoginFailedException("Failed to parse ptc error json");
            }
        }
    } catch (LoginFailedException e) {
        if (shouldRetry && attempt < MAXIMUM_RETRIES) {
            login(username, password, ++attempt);
        } else {
            throw new LoginFailedException("Exceeded maximum login retries", e);
        }
    }
}
Also used : Cookie(okhttp3.Cookie) Moshi(com.squareup.moshi.Moshi) Builder(okhttp3.FormBody.Builder) FormBody(okhttp3.FormBody) Request(okhttp3.Request) IOException(java.io.IOException) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) LoginFailedException(com.pokegoapi.exceptions.request.LoginFailedException) InvalidCredentialsException(com.pokegoapi.exceptions.request.InvalidCredentialsException)

Example 42 with Credentials

use of okhttp3.Credentials in project sonarqube by SonarSource.

the class HttpConnectorTest method use_basic_authentication.

@Test
public void use_basic_authentication() throws Exception {
    answerHelloWorld();
    underTest = HttpConnector.newBuilder().url(serverUrl).credentials("theLogin", "thePassword").build();
    GetRequest request = new GetRequest("api/issues/search");
    underTest.call(request);
    RecordedRequest recordedRequest = server.takeRequest();
    assertThat(recordedRequest.getHeader("Authorization")).isEqualTo(basic("theLogin", "thePassword"));
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Test(org.junit.Test)

Example 43 with Credentials

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

the class HttpTest method badCredsCookieThrows.

/**
 * Test that cookie authentication throws a CouchDbException if the credentials were bad.
 *
 * @throws Exception
 */
@TestTemplate
public void badCredsCookieThrows() {
    mockWebServer.enqueue(new MockResponse().setResponseCode(401));
    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer).username("bad").password("worse").build();
    CouchDbException re = assertThrows(CouchDbException.class, () -> c.executeRequest(Http.GET(c.getBaseUri())).responseAsString(), "Bad credentials should throw a CouchDbException.");
    assertTrue(re.getMessage().startsWith("401 Credentials are incorrect for server"), "The " + "exception should have been for bad creds.");
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) CouchDbException(com.cloudant.client.org.lightcouch.CouchDbException) CloudantClient(com.cloudant.client.api.CloudantClient) TestTemplate(org.junit.jupiter.api.TestTemplate)

Example 44 with Credentials

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

the class CloudantClientTests method testBasicAuthFromCredentials.

/**
 * Test that configuring the Basic Authentication interceptor from credentials and adding to
 * the CloudantClient works.
 */
@Test
public void testBasicAuthFromCredentials() throws Exception {
    BasicAuthInterceptor interceptor = BasicAuthInterceptor.createFromCredentials("username", "password");
    // send back a mock OK 200
    server.enqueue(new MockResponse());
    CloudantClient client = CloudantClientHelper.newMockWebServerClientBuilder(server).interceptors(interceptor).build();
    client.getAllDbs();
    // expected 'username:password'
    assertEquals("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", server.takeRequest().getHeader("Authorization"));
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) BasicAuthInterceptor(com.cloudant.http.interceptors.BasicAuthInterceptor) CloudantClient(com.cloudant.client.api.CloudantClient) Test(org.junit.jupiter.api.Test)

Example 45 with Credentials

use of okhttp3.Credentials in project instagram-java-scraper by postaddictme.

the class Instagram method login.

public void login(String username, String password) throws IOException {
    if (username == null || password == null) {
        throw new InstagramAuthException("Specify username and password");
    } else if (this.csrf_token.isEmpty()) {
        throw new NullPointerException("Please run before base()");
    }
    RequestBody formBody = new FormBody.Builder().add("username", username).add("password", password).add("queryParams", "{}").add("optIntoOneTap", "true").build();
    Request request = new Request.Builder().url(Endpoint.LOGIN_URL).header(Endpoint.REFERER, Endpoint.BASE_URL + "/accounts/login/").post(formBody).build();
    Response response = executeHttpRequest(withCsrfToken(request));
    try (InputStream jsonStream = response.body().byteStream()) {
        if (!mapper.isAuthenticated(jsonStream)) {
            throw new InstagramAuthException("Credentials rejected by instagram", ErrorType.UNAUTHORIZED);
        }
    }
}
Also used : Response(okhttp3.Response) ActionResponse(me.postaddict.instagram.scraper.model.ActionResponse) InstagramAuthException(me.postaddict.instagram.scraper.exception.InstagramAuthException) DataInputStream(java.io.DataInputStream) InputStream(java.io.InputStream) FormBody(okhttp3.FormBody) GetMediaByTagRequest(me.postaddict.instagram.scraper.request.GetMediaByTagRequest) GetLocationRequest(me.postaddict.instagram.scraper.request.GetLocationRequest) GetMediasRequest(me.postaddict.instagram.scraper.request.GetMediasRequest) GetMediaLikesRequest(me.postaddict.instagram.scraper.request.GetMediaLikesRequest) Request(okhttp3.Request) GetFollowsRequest(me.postaddict.instagram.scraper.request.GetFollowsRequest) GetFollowersRequest(me.postaddict.instagram.scraper.request.GetFollowersRequest) RequestBody(okhttp3.RequestBody)

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