简体   繁体   English

使用Facebook OAuth 2.0 - 如何获取访问令牌?

[英]Using Facebook OAuth 2.0 - How do I fetch the access token?

I am new to OAuth , and I'm trying to use Facebook Connect with my web-application. 我是OAuth的新手,我正在尝试将Facebook Connect与我的网络应用程序一起使用。

I have succeded in getting a verification token, but my problem is "fetching" the access token. 我已成功获得验证令牌,但我的问题是“获取”访问令牌。 How do I fetch it? 我该如何获取它? The Facebook documentation tells me to fetch the access token with this URL: Facebook文档告诉我使用以下URL获取访问令牌:

https://graph.facebook.com/oauth/access_token?'
                + 'client_id=XXXXXXXXXXXX& redirect_uri=http://www.mysite.com/fbconn/index.html&display=touch&'
                + 'client_secret=axxxxxcxxxxxxxxxxx&code=' + code;

When I use this I see the access token on a blank page, but I want to fetch it with JavaScript (Ajax), PHP or something. 当我使用它时,我在空白页面上看到访问令牌,但我想用JavaScript(Ajax),PHP或其他东西来获取它。 Is this possible? 这可能吗? I thought the access token would be appended to my redirect URI like the verfication code, but I never get redirected to my page. 我认为访问令牌将附加到我的重定向URI,如验证代码,但我从未被重定向到我的页面。 What am I doing wrong? 我究竟做错了什么?

You need to add &type=user_agent to the request. 您需要在请求中添加&type=user_agent You will get the AuthToken with a hash marker in the following format. 您将使用以下格式的哈希标记获取AuthToken。

http://yourredirecturi#code=[accesstoken]

If you set the request to &type=web_server , you'll get the AuthToken as a query string parameter: http://yourredirecturi&code=[accesstoken] . 如果将请求设置为&type=web_server ,则会将AuthToken作为查询字符串参数: http://yourredirecturi&code=[accesstoken]

Here is a full explanation of how to implement the Facebook's OAuth protocol. 以下是如何实施Facebook的OAuth协议的完整说明。 The code samples are in ASP.NET MVC, but it should translate well enough to any language: 代码示例在ASP.NET MVC中,但它应该能够很好地翻译成任何语言:

Facebook Platform's OAuth 2.0 Protocol and ASP.NET MVC Facebook平台的OAuth 2.0协议和ASP.NET MVC

Feel free to try the following PHP snippet for getting your access token: 您可以尝试使用以下PHP代码段来获取访问令牌:

//Fill in the parts in caps with your app details
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&client_secret=YOUR_APP_SECRET&code=THE_CODE_YOU_GOT_FROM_THE_SERVER";

$token=file_get_contents($token_url); //Fetching the token from the URL

echo $token; //This is your access token

Thanks, 谢谢,

$token = file_get_contents("the access token URL"); 

会给你访问令牌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM