在didFinishLaunchingWithOptions中检查无效的用户令牌Firebase

时间:2018-11-20 17:44:37

标签: ios firebase firebase-authentication google-cloud-firestore firebase-security-rules

根据Google支持,检测已撤消的Firebase令牌的唯一方法是对我的Firestore进行 read-request ,并获取 FIRAuthErrorCodeUserTokenExpired < / strong>错误。

我在iOS应用的 didFinishLaunchingWithOptions()中尝试了此操作。数据已正确读取,但是当我停用测试用户帐户(令牌应被撤销)时应该出现错误。不幸的是,Firebase仍然可以处理请求并登录用户而不会引发错误。

对于应该尽可能安全的应用程序,即使您的令牌已被撤消,如果您仍然登录该应用程序,则不是最佳选择。

这是我的代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    FirebaseApp.configure()
    window = UIWindow()
    if Auth.auth().currentUser == nil { // check if there is a User logged in
        window?.rootViewController = LoginViewController() // set the MainTabBarController as the root (start) controller
    } else{
        if let uid = Auth.auth().currentUser?.uid{
            let firRef = Firestore.firestore().collection("idols").document(uid)
            firRef.getDocument { (document, error) in
                if let err = error {
                    print(err)
                    self.window?.rootViewController = LoginViewController()
                }else{
                    guard let doc = document, let data = doc.data() else {return}
                    guard let username = data["username"] as? String, let uid = data["uid"] as? String, let biography = data["biography"] as? String else {return}
                    self.activeUser = User(uid: String(uid), username: username, biography: biography)
                    print(self.activeUser)
                    self.window?.rootViewController = MainTabBarController()
                }
            }
        }
        window?.rootViewController = LoginViewController()
    }


    return true
}

这是我的Firebase规则:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.uid != null;
    }
  }
}

我知道规则还没有完全调整,但是在我眼里,随着令牌过期,Firebase应该会抛出错误。我知道我尚未检查正确的错误,但是无论如何都不会调用 if let

我检查了包括与该主题相对应的Firebase documentation在内的多个资源,但是文档仅涵盖如何在Web上而不是在iOS或Android上检测已吊销的令牌。

除此之外,我检查了一个stack overflow条目,但是没有正确的答案,因此我决定在此处张贴自己的答案:

有人知道在iOS上出现吊销令牌后立即检测吊销令牌的正确方法吗?

很抱歉,如果这个问题的表述不够理想。我还是堆栈溢出的新手,所以请客气:)

1 个答案:

答案 0 :(得分:0)

我找到了以下解决方案:

didFinishLaunchingWithOptions 中添加以下代码:

if Auth.auth?.currentUser == nil {
   // You need to prompt the user login interface
} else {
  Auth.auth().currentUser?.reload(completion: { (error) in
    if error != nil {
        if let err = error as NSError?{
            if let error = AuthErrorCode(rawValue: err.code){
                switch error{
                // You need to prompt the user login interface
                case .invalidCredential: print("Invalid credentials")
                case .invalidUserToken: print("Invalid User Token")
                case .userTokenExpired: print("User Token Expired")
                case .invalidCustomToken: print("Invalid Custom Token")
                case .customTokenMismatch: print("Custom token mismatch")
                case .userDisabled: print("User disabled")
                case .userNotFound: print("User not found")
                default: print("call default error")
                }
            }
        }
    }
    else {
        print("Valid Token")
    }
  })
}

啊,不要忘记在运行此代码之前初始化Firebase (否则您将无权访问Firebase Auth)