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

时间:2016-06-27 17:39:04

标签: c# facebook facebook-graph-api httpwebrequest httpwebresponse

转到下方查看答案

我的Facebook访问令牌很好,但我遇到麻烦的地方是我试图自动化这个过程。

如果我访问此URL是浏览器,我就可以获得访问令牌了。

示例:

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

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

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

Viola访问令牌!

我要做的是用代码复制相同的行为。我越来越近但不太相似。

我一直收到user_denied错误。

%3Ferror%3Daccess_denied%26error_code%3D200%26error_description%3DPermissions%2Berror%26error_reason%3Duser_denied%23_%3D_&安培;显示=页面&安培;语言环境= EN_US&安培; logger_id = 786a3153-1d81-415c-8dca-f8fa8b0cd630

我正在将所有标题输出到控制台。这是我关注的位置标题**

我认为它与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错误。但是在浏览器中我得到了一个非常好的令牌。我无法弄清楚为什么。

enter image description here

使用浏览器时,位置标题中的标题似乎有效。

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

1 个答案:

答案 0 :(得分:-1)

  

此代码将自动检索access_token。您必须拥有要为其申请访问令牌的帐户的凭据。

<强>更新

首次登录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)
        );
    }