阅读 770

ios facebook登录及后台验证 Sign in with Facebook(swift)

官方:developers.facebook.com/docs/facebo…

参考:www.jianshu.com/p/663e13104…

ios端

准备

1.在Facebook登录,注册和配置项目,包括Xcode中Info.plist配置

developers.facebook.com/docs/facebo…

2.Xcode中双击项目,右边选中“Info”→“URL Types”→填写“URL Schemes”;“URL Schemes”来自于 1中的fb[APP_ID] 格式:fb2014042434534780

3.依赖

pod 'FBSDKLoginKit'
复制代码

代码

启用Sign in

1.AppDelegate配置使用facebook sdk

AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
	      //facebook,facebook sign in
        ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
        return true
}

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        //google sign in
        var handled = GIDSignIn.sharedInstance().handle(url)
        //Facebook 统计,Facebook sign in
        if (!handled) {
            handled = ApplicationDelegate.shared.application(
                app,
                open: url,
                sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
                annotation: options[UIApplication.OpenURLOptionsKey.annotation]
            )
        }
        return handled
    }
复制代码

调用sign in

1.通过自定义UIButton请求登录并接收回调

ViewController.swift
override func viewDidLoad() {
	super.viewDidLoad()
	button.addTarget(self, action: #selector(facebookSignIn()), for: UIControl.Event.touchUpInside)
}
@objc private func fbClick(){
        mFbLoginManager = LoginManager()
        mFbLoginManager.logIn(permissions: ["public_profile", "email"], from: self) { (loginResult, error) in
            if error != nil {
                DLOG(self.LOGTAG, "facebook login error")
            } else {
                if let result = loginResult {
                    if result.isCancelled {
                        DLOG(self.LOGTAG, "facebook login cancelled")
                    } else {
                        DLOG(self.LOGTAG, "facebook is login in")
                        Profile.loadCurrentProfile { (profile, error) in
                            if let profile = profile {
                                let name: String = profile.name ?? ""
                                if let current = AccessToken.current {
                                    let userId: String = String(describing: current.userID)
                                    let token: String = String(describing: current.tokenString)
                                    // token 可在此发送到后台进行验证
                                }
                            }
                        }
                    }
                }
            }
        }
    }
复制代码

2.通过FBLoginButton和LoginButtonDelegate来调用sign和代理监听回调

//NotificationCenter可以监听facebook更新状态
//AccessToken.current可以获取当前token
NotificationCenter.default.addObserver(forName: .AccessTokenDidChange, object: nil, queue: OperationQueue.main) { (notification) in
            if let current = AccessToken.current, !token.isExpired  {
                let appId: String = String(describing: current.appID)
                let userId: String = String(describing: current.userID)
                let token: String = String(describing: current.tokenString)
                DLOG(self.LOGTAG, "facebook Observer appId: \(appId); userId: \(userId); token: \(token)")
            }
        }
复制代码

后端token验证(java)

官方:developers.facebook.com/docs/facebo…

public class FacebookIdentity {
    String userId;
    String clientId;//ios FacebookAppID
    String identityToken;//ios sign in 后返回的token
}

public class FacebookTokenService {

    private String accessUrl = "https://graph.facebook.com/v10.0/oauth/access_token";
    public Result verifyToken(FacebookIdentity facebookIdentity){
        try {
            //获取访问口令accessToken
            String url = accessUrl + "?grant_type=fb_attenuate_token&client_id=" + facebookIdentity.getClientId() + "&fb_exchange_token=" + facebookIdentity.getIdentityToken();
            String str = HttpClientUtils.doGet(url);
            if (str == null || str.isEmpty()) {
                return Result.fail("facebook验证 获取访问口令accessToken出错");
            }
            JSONObject data1 = JSONObject.parseObject(str);
            System.err.println("fb Response1 =====>" + JSONObject.toJSONString(data1));
            String access_token = data1.getString("access_token");
            int expires_in = data1.getIntValue("expires_in");
            if (access_token != null && expires_in > 0) {
                return Result.success("facebook token有效");
            }else {
                return Result.fail("facebook token无效或过期");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.fail("facebook验证 请求出错");
        }
    }
}

Response
{
  "access_token":"{session-info-access-token}",
  "token_type": "bearer",
  "expires_in": 5183944            //The number of seconds until the token expires
}
复制代码
文章分类
iOS
文章标签