我正在编写一个在Windows计算机上运行的.NET应用程序。它无法通过浏览器访问。问题是,我不能像我应该的那样进行身份验证。我目前正在使用C#.NET编写代码,在C#中更具体。
这是出错的地方。使用此代码,我想获得一个访问令牌。
生成的请求网址如下所示: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;
}
}
}
}
当我执行此操作时,我收到此错误:
Webexception未被用户代码处理 远程服务器返回错误:(400)错误请求。
以下是我认为可能出错的地方:
http://localhost
,即使实际上没有服务在那里收听吗?最重要的是:
提前致谢!
答案 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的编码现在变得更加容易。