使用 OAUTH 2.0 验证并从 Facebook cookie 获取数据

2023-12-20

我有一个用 GWT 制作的网页。在那里,我使用所有登录 facebook 的东西和一个受操纵的 gwtfb 库,一切正常。迁移到 oauth 2.0 后,发送到服务器的 cookie 已更改为加密的 cookie。

我想要一个java示例代码来实现在服务器中与旧的相同:

  • 我需要像使用 cookie md5 技巧之前那样验证调用,以了解调用是否是由我的客户端页面进行的。
  • 从该 cookie 获取数据:我需要 Facebook 用户。

如果可能的话不调用FB,只使用cookie数据。

提前致谢。


好吧,虽然我有一些很好的答案,但我还是用我在博客中写的内容来回答自己:http://pablocastilla.wordpress.com/2011/09/25/how-to-implement-oauth-f/ http://pablocastilla.wordpress.com/2011/09/25/how-to-implement-oauth-f/

现在cookie发生了很大的变化:它被加密了,没有accesstoken,而且它的内容格式也发生了很大的变化。这里有一些讨论它的链接:

http://developers.facebook.com/docs/authentication/signed_request/ http://developers.facebook.com/docs/authentication/signed_request/

http://developers.facebook.com/docs/authentication/ http://developers.facebook.com/docs/authentication/

http://blog.sociablelabs.com/2011/09/19/server-side-changes-facebook-oauth-2-0-upgrade/ http://blog.sociablelabs.com/2011/09/19/server-side-changes-facebook-oauth-2-0-upgrade/

因此,要验证 cookie、从中获取用户并获取访问令牌,您可以使用以下代码:

public class FaceBookSecurity {

// return the fb user in the cookie.
public static String getFBUserFromCookie(HttpServletRequest request)
        throws Exception {
    Cookie fbCookie = getFBCookie(request);

    if (fbCookie == null)
        return null;

    // gets cookie value
    String fbCookieValue = fbCookie.getValue();

    // splits it.
    String[] stringArgs = fbCookieValue.split("\\.");
    String encodedPayload = stringArgs[1];

    String payload = base64UrlDecode(encodedPayload);

    // gets the js object from the cookie
    JsonObject data = new JsonObject(payload);

    return data.getString("user_id");

}

public static boolean ValidateFBCookie(HttpServletRequest request)
        throws Exception {

    Cookie fbCookie = getFBCookie(request);

    if (fbCookie == null)
        throw new NotLoggedInFacebookException();

    // gets cookie information
    String fbCookieValue = fbCookie.getValue();

    String[] stringArgs = fbCookieValue.split("\\.");
    String encodedSignature = stringArgs[0];
    String encodedPayload = stringArgs[1];

    //decode
    String sig = base64UrlDecode(encodedSignature);
    String payload = base64UrlDecode(encodedPayload);

    // gets the js object from the cookie
    JsonObject data = new JsonObject(payload);

    if (!data.getString("algorithm").Equals("HMAC-SHA256")) {
        return false;
    }

    SecretKey key = new SecretKeySpec(
            ApplicationServerConstants.FacebookSecretKey.getBytes(),
            "hmacSHA256");

    Mac hmacSha256 = Mac.getInstance("hmacSHA256");
    hmacSha256.init(key);
    // decode the info.
    byte[] mac = hmacSha256.doFinal(encodedPayload.getBytes());

    String expectedSig = new String(mac);

    // compare if the spected sig is the same than in the cookie.
    return expectedSig.equals(sig);

}

public static String getFBAccessToken(HttpServletRequest request)
        throws Exception {
    Cookie fbCookie = getFBCookie(request);

    String fbCookieValue = fbCookie.getValue();

    String[] stringArgs = fbCookieValue.split("\\.");
    String encodedPayload = stringArgs[1];

    String payload = base64UrlDecode(encodedPayload);

    // gets the js object from the cookie
    JsonObject data = new JsonObject(payload);

    String authUrl = getAuthURL(data.getString("code"));
    URL url = new URL(authUrl);
    URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(),
            url.getQuery(), null);
    String result = readURL(uri.toURL());

    String[] resultSplited = result.split("&");

    return resultSplited[0].split("=")[1];

}

// creates the url for calling to oauth.
public static String getAuthURL(String authCode) {
    String url = "https://graph.facebook.com/oauth/access_token?client_id="
            + ApplicationConstants.FacebookApiKey
            + "&redirect_uri=&client_secret="
            + ApplicationServerConstants.FacebookSecretKey + "&code="
            + authCode;

    return url;
}

// reads the url.
private static String readURL(URL url) throws IOException {

    InputStream is = url.openStream();

    InputStreamReader inStreamReader = new InputStreamReader(is);
    BufferedReader reader = new BufferedReader(inStreamReader);

    String s = "";

    int r;
    while ((r = is.read()) != -1) {
        s = reader.readLine();
    }

    reader.close();
    return s;
}

private static String base64UrlDecode(String input) {
    String result = null;
    Base64 decoder = new Base64(true);
    byte[] decodedBytes = decoder.decode(input);
    result = new String(decodedBytes);
    return result;
}

    private static Cookie getFBCookie(HttpServletRequest request) 
    {
        Cookie[] cookies = request.getCookies();

        if (cookies == null)
            return null;

        Cookie fbCookie = null;

        for (Cookie c : cookies) {
            if (c.getName().equals(
                "fbsr_" + ApplicationServerConstants.FacebookApiKey)) {
                fbCookie = c;
            }
        }
        return fbCookie;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 OAUTH 2.0 验证并从 Facebook cookie 获取数据 的相关文章

随机推荐

  • Silverlight+WCF异常:期望应用程序/soap+xml,收到文本/xml

    我有一个 Silverlight 应用程序 我想在其中调用 WCF 服务 调用该服务时 我收到来自服务器的以下响应 415 无法处理消息 因为内容类型为 text xml charset utf 8 不是预期的类型 application
  • 从 Fluent Nhibernate 生成 XML 映射

    如何生成 xml 映射文件作为 MappingIntegrationTests 中测试的一部分 我需要手动检查流畅映射是否与遗留项目中的映射相关 你可以这样做 config Mappings m gt m FluentMappings Ex
  • 在 cp1252 上强制使用 UTF-8 (Python3)

    我编写了一些使用 Biopython Entrez 包装器的代码 代码在我以前的 Win10 笔记本电脑 Python 3 5 1 上运行良好 但我刚刚将代码移植到安装了相同版本的每个包和 Python 的新 Win10 笔记本电脑上 现在
  • 关联/随机访问容器

    我正在寻找一种数据结构来保存唯一元素的无序集合 它将支持以下操作 集合中任意位置的元素插入 删除 查询元素是否存在 访问随机元素 天真地 1 和 2 建议使用关联容器 例如unordered set 但 3 的元素数量是线性的 使用随机访问
  • 如何在 Google Maps API 中使信息窗口可编辑?

    我想在单击信息窗口时使其可编辑 这是我的代码
  • 突出显示CSS网格[关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我有 CSS 网格 div style display grid class scEnabledChrome div when I
  • 如何指定列表选择方法?

    我有一个计算列表的方法 在算法中的某些点 需要从列表中选择单个元素 选择哪个元素并不重要 但我想将其留给用户来决定 现在 我添加了一个扩展方法IList
  • 使用 jQuery 检测 iPhone 滑动

    我只是在寻找一个能够检测手指在触摸设备上滑动的监听器 例如 if swipe direction left function 通过 jQueryMobile 您可以使用多个事件 例如swipe 甚至swipeleft swiperight
  • 如何将可变数量的参数从一个函数传递到另一个函数?

    有没有办法直接将可变数量的参数从一个函数传递到另一个函数 我想实现一个最小的解决方案 如下所示 int func1 string param1 int status STATUS 1 func2 status param1 我知道我可以使用
  • 如何从 pyuic .py 文件重建 .ui 文件

    不久前我用 PyQt 做了一个项目 我创建了一些 ui 文件并使用 pyuic4 生成了相应的 py 文件 我想再次开始工作 但我丢失了 ui 文件 我格式化了我的电脑并进行了备份 但 ui 文件驻留在 Qt 设计器文件夹中并丢失了 有什么
  • 如何在 VS Code 中获取当前主题的颜色?

    我正在尝试更改 VS Code 实例中的某些颜色 我知道如何改变颜色 workbench colorCustomizations 设置 道具名称 https code visualstudio com docs getstarted the
  • 检测国际键盘的出现和消失

    当键盘出现时 有没有办法检测它是国际键盘 普通键盘顶部有一条额外的丝带以显示国际字符 并获取它的框架大小 我需要使用该信息向上移动 如果需要 键盘上方的视图 看看这篇文章 http mobile tutsplus com tutorials
  • 如何检测 iPhone 上是否连接了硬件键盘? [复制]

    这个问题在这里已经有答案了 可能的重复 iPad 检测是否存在外部键盘 https stackoverflow com questions 2893267 ipad detect if external keyboard is presen
  • 如何使用 ASP MVC Complete Wrapper 设置 Kendo UI Grid 的高度

    我正在使用 KendoUI Grid 及其 ASP MVC Complete Wrapper 库 但在剃刀代码中设置网格高度时遇到问题 我尝试设置 HTMLAttribute 但似乎不起作用 Html Kendo Grid
  • VBA上次更改方法

    我正在寻找一个在评论框中打印的功能 谁是更改该单元格数据的用户 我现在所拥有的是这样的 Private Sub Worksheet Change ByVal Target As Range If Range A Target Row Val
  • 比较两个列表并使用 powershell 查找列表一中的名称而不是列表二中的名称

    只是想知道你是否可以帮助我 我正在尝试比较两个列表 txt文件 并找到列表A中而不是列表B中的字符串并将其输出到另一个txt文件 任何人都知道如何使用电源外壳 这是我到目前为止所拥有的 Compare Object ReferenceObj
  • 通过 NSDate 对 UITableView(核心数据)进行排序

    在这个例子中 假设我有一个按钮 每次按下它都会添加一个NSDate到核心数据实体中 我也有一个TableView显示该实体的所有成员 我该如何排序TableView by NSDate 出来的格式如下 2011 08 09 21 52 13
  • 隐藏的 Cytoscape 图表稍后无法显示

    我有 2 个 Bootstrap 列 每个宽度为 12 中的 6 左边的一列有一些按钮 右边的一列包含一个用 5 个节点初始化的 Cytoscape 图 最初 当页面加载完成时 Cytoscape 图形被设置为隐藏 cyto div hid
  • 将列表文件取消列出到多个数据帧[重复]

    这个问题在这里已经有答案了 我创建了一个包含 72 个元素的 R 列表 如何将此文件取消列出到 72 个单个数据帧以及每个元素的名称 这是一个例子 L lt list data frame matrix 1 4 2 2 data frame
  • 使用 OAUTH 2.0 验证并从 Facebook cookie 获取数据

    我有一个用 GWT 制作的网页 在那里 我使用所有登录 facebook 的东西和一个受操纵的 gwtfb 库 一切正常 迁移到 oauth 2 0 后 发送到服务器的 cookie 已更改为加密的 cookie 我想要一个java示例代码