Facebook 访问令牌 - 自动获取令牌

Facebook Access Token - Automate Getting the Token

往下看答案

我可以很好地获取 Facebook 访问令牌,但是当我尝试自动执行此过程时,我遇到了麻烦。

如果我访问这个 URL 是浏览器,我就可以很好地获得访问令牌。

示例:

我将其粘贴到浏览器中并点击 return。

https://www.facebook.com/dialog/oauth?client_id=324234343434&scope=['ads_read', 'ads_management']&redirect_uri=http://www.kb-demos.com/login_success.html&response_type=token

然后我被发送到这个页面:

http://www.kb-demos.com/login_success.html?#access_token=34543534534534KJ534LKJLKJLKHLH4534534J5KH345KJ3L4H53KJ5H3K4LJH34KH54K&expires_in=5180653

我更改了访问令牌部分,因此它不是真正的令牌

中提琴访问令牌!

我想做的是用代码复制同样的行为。我越来越近了,但还不够。

我一直收到 user_denied 错误。

%3Ferror%3Daccess_denied%26error_code%3D200%26error_description%3DPermissions%2Berror%26error_reason%3Duser_denied%23_%3D_&display=page&locale =en_US&logger_id=786a3153-1d81-415c-8dca-f8fa8b0cd630

我正在将所有 header 输出到控制台。是我关心的位置header**

我认为这与 302 重定向有关?

ApplicationId = request.ClientId;
string permissions = "['ads_management', 'ads_read']";

var destinationURL = String.Format(
@"https://www.facebook.com/dialog/oauth?client_id={0}&scope={1}&redirect_uri=http://www.kb-demos.com/login_success.html&response_type=token",
ApplicationId,
permissions);

// Create a new 'HttpWebRequest' Object to the mentioned URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(destinationURL);
myHttpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36";

myHttpWebRequest.AllowAutoRedirect = false;
// Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

//Console.WriteLine("\nThe HttpHeaders are \n\n\tName\t\tValue\n{0}", myHttpWebRequest.Headers); // my http headers
// Print the HTML contents of the page to the console. 


var headers = myHttpWebResponse.Headers;

// output all the headers
foreach(var header in headers) {
    Console.WriteLine(header.ToString() + ": " + headers[header.ToString()] + "\n" );

}

#region
//Stream streamResponse = myHttpWebResponse.GetResponseStream();
//StreamReader streamRead = new StreamReader(streamResponse);
//Char[] readBuff = new Char[256];
//int count = streamRead.Read(readBuff, 0, 256);
//Console.WriteLine("\nThe HTML contents of page the are  : \n\n ");
//while (count > 0)
//{
//    String outputData = new String(readBuff, 0, count);
//    Console.Write(outputData);
//    count = streamRead.Read(readBuff, 0, 256);
//}
//// Close the Stream object.
//streamResponse.Close();
//streamRead.Close();
// Release the HttpWebResponse Resource.
#endregion


myHttpWebResponse.Close();

Console.ReadLine();

我在这里遇到 user_denied 错误。但在浏览器中,我得到了一个非常好的令牌。我不知道为什么。

位置header中的header在使用浏览器时似乎有效。

如果我无法使上述工作正常,可能出现的情况: 我想知道是否有带有 API 的浏览器?我可以从命令行调用的东西 - 传递一些参数 - 然后获得重定向 url 是要解析的变量吗?

This code will automate the retrieval of the access_token. You must have credentials to the account you are requesting an access token for.

已更新

首先登入facebook帐号。

        // LOG INTO FACEBOOK ACCT
        string email = "youremail@blah.com";
        string pw = "yourPassWord";

        CookieContainer cookieJar = new CookieContainer();

        HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create("https://www.facebook.com");
        request1.CookieContainer = cookieJar;

        request1.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36";

        //Get the response from the server and save the cookies from the first request..
        HttpWebResponse response = (HttpWebResponse)request1.GetResponse();
        var cookies = response.Cookies;
        cookieJar.Add(cookies);
        response.Close();// close the response


        string getUrl = "https://www.facebook.com/login.php?login_attempt=1";

        string postData = String.Format("email={0}&pass={1}", email, pw);
        HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
        getRequest.CookieContainer = cookieJar;
        //Adding Previously Received Cookies 
        getRequest.CookieContainer.Add(cookies);
        getRequest.Method = WebRequestMethods.Http.Post;
        getRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36";
        getRequest.AllowWriteStreamBuffering = true;
        getRequest.ProtocolVersion = HttpVersion.Version11;
        getRequest.AllowAutoRedirect = true;
        getRequest.ContentType = "application/x-www-form-urlencoded";

        byte[] byteArray = Encoding.ASCII.GetBytes(postData);
        getRequest.ContentLength = byteArray.Length;
        Stream newStream = getRequest.GetRequestStream(); //open connection
        newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
        newStream.Close();

        HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
        using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
        {
            string sourceCode = sr.ReadToEnd();
        } 

然后请求 access_token

                ApplicationId = request.ClientId; // your application id
                string permissions = "['ads_management', 'ads_read']";

                var destinationURL = String.Format(
                @"https://www.facebook.com/dialog/oauth?client_id={0}&scope={1}&redirect_uri=http://www.kb-demos.com/login_success.html&response_type=token",
                ApplicationId,
                permissions);

                // Create a new 'HttpWebRequest' Object to the mentioned URL.
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(destinationURL);
                // use the same cookie container and cookies
                myHttpWebRequest.CookieContainer = cookieJar;
                myHttpWebRequest.CookieContainer.Add(cookies); //recover cookies First request

                myHttpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36";

                myHttpWebRequest.AllowAutoRedirect = false;
                // Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
                HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

                Console.WriteLine("\nThe Request HttpHeaders are \n\n\tName\t\tValue\n{0}", myHttpWebRequest.Headers); // my http headers
                Console.WriteLine("\nThe Request HttpHeaders are \n\n\tName\t\tValue\n{0}", myHttpWebRequest.CookieContainer); // my http headers
                //Console.WriteLine("\nThe Request HttpHeaders are \n\n\tName\t\tValue\n{0}", cookies); // my http headers

                var headers = myHttpWebResponse.Headers;
                // output all the headers
                foreach (var header in headers)
                {
                    Console.WriteLine(header.ToString() + ": " + headers[header.ToString()] + "\n");

                }

                var cow = GetParams(headers["Location"]);
                string accessToken = "";
                accessToken = cow["#access_token"];

和辅助方法

    /// <summary>
    /// Helper method to get Params from URL using RegEx
    /// </summary>
    static Dictionary<string, string> GetParams(string uri)
    {
        var matches = Regex.Matches(uri, @"[\?&](([^&=]+)=([^&=#]*))", RegexOptions.Compiled);
        return matches.Cast<Match>().ToDictionary(
            m => Uri.UnescapeDataString(m.Groups[2].Value),
            m => Uri.UnescapeDataString(m.Groups[3].Value)
        );
    }