title: Using HttpWebRequest to login to instagram
body: <p>Hey guys so I'm trying to write a C# Application in which the user can login to their instagram account from a WPF. The problem I'm having is getting the authorization code. When I use this code I keep getting the login page URL, not the successful login page. </p>
  
  <p>Help please!
  Any feedback is appreciated! been stuck on this a while</p>
  
  <pre><code>private static AuthInfo GetInstagramAuth(string oAuthUri,  string clientId, string redirectUri, InstagramConfig config,
          string login, string password)
      {
          List&lt;Auth.Scope&gt; scopes = new List&lt;Auth.Scope&gt;();
          scopes.Add(Auth.Scope.basic);
  
          var link = InstaSharp.Auth.AuthLink(oAuthUri, clientId, redirectUri, scopes);
  
          // Логинимся по указанному узлу
          CookieAwareWebClient client = new CookieAwareWebClient();
          // Зашли на страницу логина
          var result = client.DownloadData(link);
          var html = System.Text.Encoding.Default.GetString(result);
  
          // Берем токен
          string csr = "";
          string pattern = @"csrfmiddlewaretoken""\svalue=""(.+)""";
          var r = new System.Text.RegularExpressions.Regex(pattern);
          var m = r.Match(html);
          csr = m.Groups[1].Value;
  
          // Логинимся
          string loginLink = string.Format(
              "https://instagram.com/accounts/login/?next=/oauth/authorize/%3Fclient_id%3D{0}%26redirect_uri%3Dhttp%3A//kakveselo.ru%26response_type%3Dcode%26scope%3Dbasic", clientId);
  
          NameValueCollection parameters = new NameValueCollection();
          parameters.Add("csrfmiddlewaretoken", csr);
          parameters.Add("username", login);
          parameters.Add("password", password);
  
          // Нужно добавить секретные кукисы, полученные перед логином
  
          // Нужны заголовки что ли
          string agent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
          client.Headers["Referer"] = loginLink;
          client.Headers["Host"] = "instagram.com";
          //client.Headers["Connection"] = "Keep-Alive";
          client.Headers["Content-Type"] = "application/x-www-form-urlencoded";
          //client.Headers["Content-Length"] = "88";
          client.Headers["User-Agent"] = agent;
         // client.Headers["Accept-Language"] = "ru-RU";
          //client.Headers["Accept-Encoding"] = "gzip, deflate";
          client.Headers["Accept"] = "text/html, application/xhtml+xml, */*";
          client.Headers["Cache-Control"] = "no-cache";
  
          // Запрос
          var result2 = client.UploadValues(loginLink, "POST", parameters);
  
          // Постим данные, Получаем code
          // New link не на апи, а на instagram
          string newPostLink = string.Format(
              "https://instagram.com/oauth/authorize/?client_id={0}&amp;redirect_uri=http://kakveselo.ru&amp;response_type=code&amp;scope=basic", clientId);
  
          HttpWebRequest request =
              (HttpWebRequest) WebRequest.Create(newPostLink);
          request.AllowAutoRedirect = false;
          request.CookieContainer = client.Cookies;
          request.Referer = newPostLink;
          request.Method = "POST";
          request.ContentType = "application/x-www-form-urlencoded";
          request.UserAgent = agent;
  
          string postData = String.Format("csrfmiddlewaretoken={0}&amp;allow=Authorize", csr);
          request.ContentLength = postData.Length;
  
          ASCIIEncoding encoding = new ASCIIEncoding();
          byte[] loginDataBytes = encoding.GetBytes(postData);
          request.ContentLength = loginDataBytes.Length;
          Stream stream = request.GetRequestStream();
          stream.Write(loginDataBytes, 0, loginDataBytes.Length);
  
          // send the request
          var response = request.GetResponse();
          string location = response.Headers["Location"];
  
          Console.ForegroundColor = ConsoleColor.Red;
          Console.WriteLine("--Responce from the webrequest--");
          Console.ResetColor();
          Console.WriteLine(((HttpWebResponse)response).ResponseUri+"\n\n");
  
  
          // Теперь вытаскиваем код и получаем аутентификацию
          pattern = @"kakveselo.ru\?code=(.+)";
          r = new System.Text.RegularExpressions.Regex(pattern);
          m = r.Match(location);
          string code = m.Groups[1].Value;
  
          // Наконец, получаем токен аутентификации
          var auth = new InstaSharp.Auth(config); //.OAuth(InstaSharpConfig.config);
  
          // now we have to call back to instagram and include the code they gave us
          // along with our client secret
          var oauthResponse = auth.RequestToken(code);
  
          return oauthResponse;
      }
  }
  </code></pre>
  
  <p>I was using this <a href="http://www.gotdotnet.ru/blogs/squall/13573/#comments" rel="nofollow">website</a> as an example and <code>CookieAwareWebClient</code> is just a <code>WebClient</code> that handles <code>Cookies</code>. I'll post it below:</p>
  
  <pre><code>    using System;
  /// &lt;summary&gt;
  /// A Cookie-aware WebClient that will store authentication cookie information and persist it through subsequent requests.
  /// &lt;/summary&gt;
  using System.Net;
  
  
  
  public class CookieAwareWebClient : WebClient
  {
      //Properties to handle implementing a timeout
      private int? _timeout = null;
      public int? Timeout
      {
          get
          {
              return _timeout;
          }
          set
          {
              _timeout = value;
          }
      }
  
      //A CookieContainer class to house the Cookie once it is contained within one of the Requests
      public CookieContainer Cookies { get; private set; }
  
      //Constructor
      public CookieAwareWebClient()
      {
          Cookies = new CookieContainer();
      }
  
      //Method to handle setting the optional timeout (in milliseconds)
      public void SetTimeout(int timeout)
      {
          _timeout = timeout;
      }
  
      //This handles using and storing the Cookie information as well as managing the Request timeout
      protected override WebRequest GetWebRequest(Uri address)
      {
          //Handles the CookieContainer
          var request = (HttpWebRequest)base.GetWebRequest(address);
          request.CookieContainer = Cookies;
          //Sets the Timeout if it exists
          if (_timeout.HasValue)
          {
              request.Timeout = _timeout.Value;
          }
          return request;
      }
  
  }
  </code></pre>