V
V
Viktor2016-03-28 00:15:26
Java
Viktor, 2016-03-28 00:15:26

How to log in to instagram from java, get a code and then an access token?

I use okhttp3 to work with requests.
First of all, I send a request to instagram.com and receive cookies (in which there is a csrftoken for further authorization)
Then I authorize the user by sending him a POST request to and write all the cookies to the array (if updates come, I update)
The next thing I go to the CODE receiving page (for further request for a token) and I get a default page something like prntscr.com/akttxx
Here I need to press the Authorize button by sending a request to the same post page with the parameters allow=Authorize and csrfmiddlewaretoken=csrftoken_received (Tracking the entire authorization chain through f12 using the scientific poke method I found out it's him
and here the problem appears: the following error is returned: Failed to load the page. If your browser has cookies disabled or you are using safe browser mode, try enabling cookies or turning off safe mode, and then try again.
However, if we didn't enable cookies, we wouldn't log in.
Here's an example shitcode:

Headers.Builder headers = new Headers.Builder();
        String currentCookie = "";
        get("https://www.instagram.com/", headers.build());
        csrfToken = cookies[1].toString().split("=")[1].split(";")[0];
        FormBody.Builder body = new FormBody.Builder();
        body.add("username", login);
        body.add("password", password);
        int i = 0;
        while(cookies[i] != null) {
            currentCookie += cookies[i].name()+"="+cookies[i].value()+"; ";
            i++;
        }
        currentCookie += "ig_pr=1; ig_vw=1920;";
        headers.add("cookie", currentCookie);
        headers.add("accept", "*/*");
        headers.add("origin", "https://www.instagram.com"); // получили изначальные куки
        headers.add("content-length", "19");
        headers.add("accept-language", "ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4");
        headers.add("referer", "https://www.instagram.com/");
        headers.add("user-agen", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36");
        headers.add("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        headers.add("x-csrftoken", csrfToken);
        headers.add("x-instagram-ajax", "1");
        headers.add("x-requested-with", "XMLHttpRequest");
        post("https://www.instagram.com/accounts/login/ajax/", body.build(), headers.build()); // авторизовались.
        currentCookie = "";
        i = 0;
        while(cookies[i] != null) {
            currentCookie += cookies[i].name()+"="+cookies[i].value()+"; ";
            i++;
        }
        headers = new Headers.Builder();
        currentCookie += "ig_pr=1; ig_vw=1920;";
        headers.add("cookie", currentCookie);
        headers.add("accept-language", "ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4");
        headers.add("user-agen", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36");
        headers.add("upgrade-insecure-requests", "1");
        Response rr = get("https://www.instagram.com/oauth/authorize/?client_id=976226ea8cf547a5bb2817b82a852c1e&redirect_uri=http://localhost&response_type=code", headers.build()); // попытка получить редирект на прямую
        if(rr.code() != 302) { // если попытка провалилась (пришла форма, где нам нужно нажать кнопку) - мы нажимаем на кнопку
            currentCookie = "";
            i = 0;
            while(cookies[i] != null) {
                currentCookie += cookies[i].name()+"="+cookies[i].value()+"; ";
                i++;
            }
            headers = new Headers.Builder();
            currentCookie += "ig_pr=1; ig_vw=1920; s_network=;";
            headers.add("cookie", currentCookie);
            headers.add("accept-language", "ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4");
            headers.add("user-agen", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36");
            headers.add("upgrade-insecure-requests", "1");
            headers.add("origin", "https://www.instagram.com");
            headers.add("referer", "https://www.instagram.com/oauth/authorize/?client_id=976226ea8cf547a5bb2817b82a852c1e&redirect_uri=http://localhost&response_type=code");
            headers.add("content-length", "68");
            headers.add("content-type","application/x-www-form-urlencoded; charset=UTF-8");
            headers.add("cache-control","max-age=0");
            headers.add("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            body = new FormBody.Builder();
            body.add("csrfmiddlewaretoken", csrfToken);
            body.add("allow", "Authorize");
            rr = post("https://www.instagram.com/oauth/authorize/?client_id=976226ea8cf547a5bb2817b82a852c1e&redirect_uri=http://localhost&response_type=code", body.build(), headers.build()); // вот тут приходит 403 ошибка которая гласит, что куки не включены
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
VanKrock, 2016-03-30
@VanKrock

I do not quite understand why you are making the second request through the browser? OAuth has several types of authorization: client (the application must be able to control the browser, for example, an android application or a desktop client) and server (for example, for a site to log in to your site using social networks), there is more, but it doesn’t matter here. So, as far as I understand, you use the second type, because you use code.
Algorithm of work of client authorization
Send a get request

https://www.instagram.com/oauth/authorize/
specify response_type=token
and you will be redirected to the specified redirect_uri, your token will be in the link, you will need to get it from the address
when the token expires, you just log in again and if there are cookies, the redirect will happen immediately, you can even not show the browser window to the user.
Algorithm for server authorization
Sending a get request
https://www.instagram.com/oauth/authorize/
specify response_type=code and redirect_uri=address_on_your_server_which_processes_the user's_code
will send to your server, that is, the server will send you a get request in the parameters of which will be code
and then, having received the code, you send a request to instagram from the server, indicating the code and the secret_key received during registration, upon expiration token you send a request also from the server specifying refresh_token

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question