1

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.

Help please! Any feedback is appreciated! been stuck on this a while

private static AuthInfo GetInstagramAuth(string oAuthUri,  string clientId, string redirectUri, InstagramConfig config,
        string login, string password)
    {
        List<Auth.Scope> scopes = new List<Auth.Scope>();
        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}&redirect_uri=http://kakveselo.ru&response_type=code&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}&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;
    }
}

I was using this website as an example and CookieAwareWebClient is just a WebClient that handles Cookies. I'll post it below:

    using System;
/// <summary>
/// A Cookie-aware WebClient that will store authentication cookie information and persist it through subsequent requests.
/// </summary>
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;
    }

}
Victor Sigler
  • 23,243
  • 14
  • 88
  • 105
jcjunction
  • 315
  • 3
  • 15

2 Answers2

2

Are you sure the login process on the website don't use javascript in some step(s)? As far as i'm aware, if it's the case webrequests won't do the job.

All datas/actions that are javascript related will be non-existent through mere webrequests. I noticed that for security reasons, Websites with personnal accounts tend to mix their login process with javascript now, to avoid bots requests.

Bombinosh
  • 413
  • 6
  • 18
  • I'm sure that Instagram uses javascript, but why wouldn't the webrequest work? I thought a webrequest was just like manually entering the info on the GUI, except it's "behind the scenes"?? – jcjunction Mar 17 '14 at 16:42
  • 1
    check this link : http://stackoverflow.com/questions/516027/c-sharp-httpwebrequest-and-javascript – Bombinosh Mar 17 '14 at 16:44
  • Okay thanks, that is a very helpful answer! Now I know I can use the WebBrowser Object if I need to. One more question though, ideally all i really want is the website to login then it will generate the webrequest with the users access token appended to the end of the new webaddress. So if its javascript it wouldn't ever get to that access token using WebRequests? – jcjunction Mar 17 '14 at 16:50
  • +1 thanks for your help! I think this may be the issue – jcjunction Mar 17 '14 at 18:27
1

Okay So I Figured out the issue. If you want to use webrequests and webresponses you need to make sure that the header information is correct. The issue with mine was I wasn't passing enough information from the browser. To see this information i used Tamper Data It's an add on for Firefox and allows you took look at everything you are sending or receiving to/from the server.

jcjunction
  • 315
  • 3
  • 15