Hello, I try to log in to instagram programmatically, that's what I do:

CookieDictionary cook = new CookieDictionary(); string Get() { var request = new HttpRequest(); request.Cookies = cook; //отправляем запрос HttpResponse response = request.Get("https://instagram.com/accounts/login/"); // Принимаем тело сообщения в виде строки string content = response.ToString(); string pattern = @"([0-9a-f]{32})"; Regex regex = new Regex(pattern); Match match = regex.Match(content); return match.Groups[1].Value; } void Auth() { try { string tok = Get(); var request = new HttpRequest(); request.UserAgent = HttpHelper.FirefoxUserAgent(); request.Cookies = cook; request.AddParam("username", "логин"); request.AddParam("password", "пароль"); request.AddParam("csrf_token", tok); HttpResponse response = request.Post("https://instagram.com/accounts/login/"); /*if (response.Cookies.TryGetValue("csrfmiddlewaretoken", out tok)) return true; return false;*/ } 

It gives error code 403. Can anyone have authorization examples through api? I work here with the xNet library. I read the documentation of the insta, but they do not have examples on Sharp.

  • And where did you get the idea that all this has at least something to do with the Instagram API? - user6550
  • This is not related to api. I said that this method does not work, so I ask if anyone has authorization methods via api - inkorpus
  • Konesno there. And they click for a split second where they should be: on the instagram website, under the word "API". - user6550
  • In API instagramm there is no authentication by user name and password. there is only oauth, which requires a redirect to the site instagram. Passing a username and password through a third-party application is not safe, so do not expect a simple and convenient way to do it. - PashaPash
  • one
    Fiction reading aloud documentation - special price. - user6550

1 answer 1

There is nothing especially difficult in form authentication. You can not even parse the page, and take the csrf-token from cookies.

The class used for authentication:

 using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; namespace InstagramClient { public class Instagram : IDisposable { private const string USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) "+ "AppleWebKit/537.36 (KHTML, like Gecko) "+ "Chrome/45.0.2414.0 Safari/537.36"; private HttpClientHandler m_handler; private HttpClient m_client; /// <summary> /// Http-клиент, который после аунтификации /// можно использовать для выполнения /// различных действий на сайте . /// </summary> public HttpClient Client { get { return m_client; } } public Instagram() { m_handler = new HttpClientHandler(); m_client = new HttpClient(m_handler); m_client.BaseAddress = new Uri("https://instagram.com/"); m_client.DefaultRequestHeaders.UserAgent.ParseAdd(USER_AGENT); } public void Dispose() { m_client.Dispose(); m_handler.Dispose(); } /// <summary> /// Осуществляет вход в Instagram, /// аналогично использованию стандартной формы логина в браузере /// </summary> /// <param name="username">Логин либо e-mail</param> /// <param name="password">Пароль</param> /// <returns></returns> public async Task<bool> LoginAsync(string username, string password) { // получаем страницу входа, что бы сайт установил Cookie 'csrftoken' // содержимое страницы нам не важно await m_client.GetAsync("/accounts/login/"); // получаем токен из Cookies var cookies = m_handler.CookieContainer.GetCookies(m_client.BaseAddress); var csrftoken = cookies["csrftoken"].Value; // готовим поля для формы входа var fields = new Dictionary<string, string>() { { "username", username }, { "password", password } }; // готовим запрос var request = new HttpRequestMessage(HttpMethod.Post, "/accounts/login/ajax/"); request.Content = new FormUrlEncodedContent(fields); request.Headers.Referrer = new Uri(m_client.BaseAddress, "/accounts/login/"); // Дополнительные заголовки запроса. // Кроме X-CSRFToken, остальное в общем-то не обязательно. request.Headers.Add("X-CSRFToken", csrftoken); request.Headers.Add("X-Instagram-AJAX", "1"); request.Headers.Add("X-Requested-With", "XMLHttpRequest"); // Авторзуемся через AJAX var response = await m_client.SendAsync(request); var info = JsonConvert.DeserializeObject<LoginInfo>(await response.Content.ReadAsStringAsync()); return info.authenticated; } private class LoginInfo { public string status { get; set; } public bool authenticated { get; set; } } } } 

Well, in case of successful authentication, we use Client to receive / send the information we need:

 using (var instagram = new Instagram()) { if (await instagram.LoginAsync("User", "Pa$$word")) { var homepage = await instagram.Client.GetStringAsync("/"); /* ... */ } } 

Well, about the API:

  1. register yourself

  2. register a new client (ibid. specify redirect-uri)

  3. see the documentation and call the methods you need

Redirect-uri when authorizing sites is equal to the handler on the server. When authorizing applications, it can be practically equal to anything (even if it does not exist, if you have control over client requests), the main thing is that you could pull ACCESS-TOKEN from the URL to which instagram will redirect you.

  • Sergey, now tell me the code is relevant? or instagram added an extra check? ps my code does not work, although in appearance it is correct. - Anonymous
  • @hitcode, no longer. ru.stackoverflow.com/a/486617/17298 - here is more relevant. Now checked - the code from that answer is quite working. - Sergey Rufanov
  • thanks Sereg, otherwise nobody helps comrades to programmers. =) - Anonymous