Facebook 第三方授权登录

创建应用

地址

配置应用
 

获得应用密钥

前端获得授权地址
 

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Facebook Login</title>
  </head>
  <body>

    <h2>Facebook Login</h2>

    <!-- Button to trigger Facebook login -->
    <button id="loginBtn">Login with Facebook</button>

    <!-- Set the element id for the JSON response -->
    <p id="profile"></p>

    <script>
      // Add the Facebook SDK for Javascript
      (function(d, s, id){
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) { return; }
        js = d.createElement(s); js.id = id;
        js.src = "https://connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
      }(document, 'script', 'facebook-jssdk'));

      window.fbAsyncInit = function() {
        // Initialize the SDK with your app and the Graph API version for your app
        FB.init({
          appId      : '367426305825029',
          xfbml      : true,
          version    : 'v20.0'
        });

        // Check if user is logged in and if not, prompt login dialog
        FB.getLoginStatus(function(response) {
          if (response.status === 'connected') {
            // Fetch user information if already logged in
            fetchUserProfile();
          }
        });
      };

      function fetchUserProfile() {
        FB.api('/me', {fields: 'name,email'}, function(response) {
          document.getElementById("profile").innerHTML = "Good to see you, " + response.name + ". I see your email address is " + response.email;
        });
      }

      // Add event listener to login button
      document.getElementById('loginBtn').addEventListener('click', function() {
        FB.login(function(response) {
		console.log(response);
          if (response.authResponse) {
            fetchUserProfile();
          } else {
            console.log('User cancelled login or did not fully authorize.');
          }
        }, {scope: 'public_profile,email'});
      });
    </script>

  </body>
</html>

实际请求地址(把***************替换成appid)icon-default.png?t=N7T8https://www.facebook.com/login.php?skip_api_login=1&api_key=***************&kid_directed_site=0&app_id=***************&signed_next=1&next=https%3A%2F%2Fwww.facebook.com%2Fv20.0%2Fdialog%2Foauth%3Fapp_id%3D***************%26cbt%3D1716531332621%26channel_url%3Dhttps%253A%252F%252Fstaticxx.facebook.com%252Fx%252Fconnect%252Fxd_arbiter%252F%253Fversion%253D46%2523cb%253Df8fd00a97f7ff5138%2526domain%253Dtest.burlambird.com%2526is_canvas%253Dfalse%2526origin%253Dhttps%25253A%25252F%25252Ftest.burlambird.com%25252Ffad79a54afc5be057%2526relation%253Dopener%26client_id%3D***************%26display%3Dpopup%26domain%3Dtest.burlambird.com%26e2e%3D%257B%257D%26fallback_redirect_uri%3Dhttps%253A%252F%252Ftest.burlambird.com%252Ffacebook_login.html%26locale%3Den_US%26logger_id%3Df4e38733d5f69a87f%26origin%3D1%26redirect_uri%3Dhttps%253A%252F%252Fstaticxx.facebook.com%252Fx%252Fconnect%252Fxd_arbiter%252F%253Fversion%253D46%2523cb%253Dfea27904b50c99967%2526domain%253Dtest.burlambird.com%2526is_canvas%253Dfalse%2526origin%253Dhttps%25253A%25252F%25252Ftest.burlambird.com%25252Ffad79a54afc5be057%2526relation%253Dopener%2526frame%253Df9851c5dd1952394c%26response_type%3Dtoken%252Csigned_request%252Cgraph_domain%26scope%3Dpublic_profile%252Cemail%26sdk%3Djoey%26version%3Dv20.0%26ret%3Dlogin%26fbapp_pres%3D0%26tp%3Dunspecified&cancel_url=https%3A%2F%2Fstaticxx.facebook.com%2Fx%2Fconnect%2Fxd_arbiter%2F%3Fversion%3D46%23cb%3Dfea27904b50c99967%26domain%3Dtest.burlambird.com%26is_canvas%3Dfalse%26origin%3Dhttps%253A%252F%252Ftest.burlambird.com%252Ffad79a54afc5be057%26relation%3Dopener%26frame%3Df9851c5dd1952394c%26error%3Daccess_denied%26error_code%3D200%26error_description%3DPermissions%2Berror%26error_reason%3Duser_denied&display=popup&locale=zh_CN&pl_dbl=0

登录后返回参数: 

{
    "authResponse": {
        "accessToken": "****",
        "userID": "********",
        "expiresIn": *****,
        "signedRequest": "********",
        "graphDomain": "facebook",
        "data_access_expiration_time": 1724305147
    },
    "status": "connected"
}

后端验证token获取用户信息

package com.example.facebooklogin;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Map;

@RestController
public class FacebookLoginController {

    @Value("${facebook.app.id}")
    private String facebookAppId;

    @Value("${facebook.app.secret}")
    private String facebookAppSecret;

    private static final String FACEBOOK_GRAPH_API_URL = "https://graph.facebook.com/me?fields=id,name,email&access_token=";
    private static final String FACEBOOK_TOKEN_DEBUG_URL = "https://graph.facebook.com/debug_token?input_token=%s&access_token=%s|%s";

    @PostMapping("/verifyToken")
    public ResponseEntity<?> verifyFacebookToken(@RequestBody Map<String, String> request) {
        String accessToken = request.get("accessToken");

        // 先验证访问令牌的有效性
        if (!validateAccessToken(accessToken)) {
            return ResponseEntity.status(401).body("Invalid access token");
        }

        String url = FACEBOOK_GRAPH_API_URL + accessToken;
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

        if (response.getStatusCode().is2xxSuccessful()) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode userInfo = objectMapper.readTree(response.getBody());

                // 获取用户信息
                String userId = userInfo.get("id").asText();
                String userName = userInfo.get("name").asText();
                String userEmail = userInfo.get("email").asText();

                // 处理用户信息,例如在数据库中创建或更新用户
                // ...

                // 返回用户信息
                return ResponseEntity.ok(userInfo);
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseEntity.status(500).body("Error parsing user info");
            }
        } else {
            return ResponseEntity.status(response.getStatusCode()).body("Invalid access token");
        }
    }

    private boolean validateAccessToken(String accessToken) {
        String debugUrl = String.format(FACEBOOK_TOKEN_DEBUG_URL, accessToken, facebookAppId, facebookAppSecret);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity(debugUrl, String.class);

        if (response.getStatusCode().is2xxSuccessful()) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode debugInfo = objectMapper.readTree(response.getBody());
                JsonNode data = debugInfo.get("data");
                return data.get("is_valid").asBoolean();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        } else {
            return false;
        }
    }
}

需要代理在发送请求前添加以下代码
 

System.setProperty("proxyHost", "127.0.0.1"); // PROXY_HOST:代理的IP地址
System.setProperty("proxyPort", "1009"); // PROXY_PORT:代理的端口号

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值