facebook - 如何在 Javascript SDK 中设置 Facebook 访问(从服务器)

标签 facebook facebook-graph-api facebook-javascript-sdk

如果我使用服务器端流程对用户进行身份验证并获取访问 token ,我该如何在 JavaScript SDK 中设置该访问 token 并使用它从客户端进行调用?

最佳答案

一旦用户完成服务器端身份验证流程,用户就已经获得了您应用程序的授权,您需要做的就是使用 FB.getLoginStatus方法:

FB.getLoginStatus(function(response) {
    if (response.status === "connected") {
        console.log("authResponse: ", response.authResponse);
        FB.api("me", function(response2) {
            console.log("Hey there " + response2.name);
        });
    }
    else if (response.status === "not_authorized") {
        // user is logged in to facebook but hasn't authorized your app, should not happen if he went through the server side authentication
    }
    else {
        // user is logged out of facebook, also should not happen
    }
}

如您所见,您可以简单地使用 js sdk 来查询图形,无需手动获取 token ,但如果您仍然需要它,authResponse 应具有以下格式:

authResponse: {
    accessToken: "aaaaaaa",
    expiresIn: "bbbbbb",
    signedRequest: "cccccc",
    userID: "dddddd"
}

编辑

如果用户登录到 facebook 并允许您的应用程序并与之交互,那么 getLoginStatus 应该返回一个有效的访问 token 。
在少数情况下情况并非如此,其中之一是 token 已过期。

正如 Handling Invalid and Expired Access Tokens 中所述:

Desktop Web and Mobile Web apps which implement authentication with the Javascript SDK

Calling FB.getLoginStatus() or ensuring status: true is set when you call FB.init() means that the next time a user lands on your application and is signed into Facebook, the authResponse object you are passed as a result of those calls will contain a fresh, valid access token.

In this case, its simply the act of the user using your application which implicitly generates a new access token.

关于facebook - 如何在 Javascript SDK 中设置 Facebook 访问(从服务器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10886812/

相关文章:

没有 SSL 的 Facebook 登录

facebook - 使用 facebook graph api 搜索 friend

android - 使用facebook android sdk的用户手机号码

cocoa - 通过 OAuth 2.0 使用特定帐户登录 Facebook

javascript - 发送消息和在自己的墙上发帖功能不再有效

javascript - 删除 Facebook 帖子的脚本

iphone - Facebook session 代理如何提高安全性?

Android : After Callback from Facebook, 我的主要 Activity 将调用哪个状态?

swift - 在 iOS 上访问 Facebook 消息(或通知)

javascript - 如何建立 friend 和喜欢的对象