无法在.NET桌面应用程序中检索访问令牌

时间:2011-05-27 12:24:07

标签: c# .net facebook facebook-authentication

我正在编写一个在Windows计算机上运行的.NET应用程序。它无法通过浏览器访问。问题是,我不能像我应该的那样进行身份验证。我目前正在使用C#.NET编写代码,在C#中更具体。

  • 我的表单上有一个webbrowser控件。
  • 用户通过此webbrowser控件登录Facebook。
  • 登录后,我开始验证程序。
  • 然后我检索了一段代码。

这是出错的地方。使用此代码,我想获得一个访问令牌。 生成的请求网址如下所示:https://graph.facebook.com/oauth/access_token?client_id=____MY_APP_ID______&redirect_uri=http://localhost/&client_secret=_____MY_APP_SECRET_____&code=____MY_RETREIVED_CODE_____,并通过以下代码制作。

请注意,我的重定向网址为http://localhost。这应该没事,对吧?

另外,在我的应用设置中,我有以下信息。

  

网站网址:http://localhost/   站点域:localhost

private String ExchangeCodeForToken(String code, Uri redirectUrl)
{
    var TokenEndpoint = new Uri("https://graph.facebook.com/oauth/access_token");
    var url = TokenEndpoint + "?" +
                      "client_id=" + _AppID + "&" +
                      "redirect_uri=" + redirectUrl + "&" +
                      "client_secret=" + _AppSecret + "&" +
                      "code=" + code;
    var request = WebRequest.CreateDefault(new Uri(url));
    using (var response = request.GetResponse())
    {
        using (var responseStream = response.GetResponseStream())
        {
            using (var responseReader = new StreamReader(responseStream))
            {
                var responseText = responseReader.ReadToEnd();
                var token = responseText.Replace("access_token=", "");
                return token;
            }
        }
     }
}

当我执行此操作时,我收到此错误:

error http://www.imageupload.org/getfile.php?id=50131&a=447f6fcc0ebd4d3f8e8a59a3a6e36ac3&t=4de0841c&o=0889D68FDC35508BA2C6F2689FCBAB7C30A8670CC9647EE598701D8BEC13ED278F0989D393&n=autherror.png&i=1

  

Webexception未被用户代码处理   远程服务器返回错误:(400)错误请求。

以下是我认为可能出错的地方:

  • 我的应用设置是否正确?
  • 我的重定向网址应该是http://localhost,即使实际上没有服务在那里收听吗?

最重要的是:

  • 如何摆脱此错误并检索访问令牌?

提前致谢!

2 个答案:

答案 0 :(得分:2)

您收到此错误是因为您不应该从桌面应用程序调用此URL:据我所知,您无法使用令牌端点进行桌面应用程序身份验证。此外,您可以直接获取访问令牌(无需先请求代码)。这是你必须做的。

在嵌入式网络浏览器中加载以下网址:

https://www.facebook.com/dialog/oauth?
  client_id=YOUR_APP_ID&
  redirect_uri=https://www.facebook.com/connect/login_success.html

将要求用户登录并使用URL中的访问令牌重定向到此URL:

https://www.facebook.com/connect/login_success.html#access_token=...

因此,您必须检测重定向并从URL中检索访问令牌。

答案 1 :(得分:0)

谢谢quinten!

但是,我已经设法通过使用C#Facebook SDK解决了我自己的问题。 这个软件开发套件非常有用!

包含了大量样本(包括授权)

任何使用facebook在.NET中编程的人都应该检查一下! Facebook的编码现在变得更加容易。

http://facebooksdk.codeplex.com/