Check for invalid user-token firebase in didFinishLaunchingWithOptions












0















according to the Google Support, the only way to detect revoked firebase tokens is by making a read-request to my Firestore and catching back the FIRAuthErrorCodeUserTokenExpired error.



I tried it in didFinishLaunchingWithOptions() of my iOS App. The data is read correctly, but there should be an error as I deactivated the test-user account (token should be revoked). Unfortunately, Firebase still handles the request and logs in the user without throwing an error.



For an app that should be as secure as possible, it is very suboptimal if you stay logged in into the app though you're token has already been revoked.



Here is my code:



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
}


Here my Firebase Rules:



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


I am aware that the rules are not perfectly adjusted yet but in my eyes, Firebase should throw an error, as the token is expired. I am aware that I have not yet checked for the correct error but the if let does not get called anyways.



I checked multiple resources including the Firebase documentation corresponding to this topic but the documentation only covers how to detect revoked tokens in the web and not on iOS or Android.



Besides that, I checked a stack overflow entry but it had no correct answer that was helpful so I decided to post my own one here:



Does anyone know the right way how to detect revoked tokens as soon as they occur on iOS?



I am sorry if this question is not perfectly formulated. I am still new to stack overflow, so please be kind :)










share|improve this question



























    0















    according to the Google Support, the only way to detect revoked firebase tokens is by making a read-request to my Firestore and catching back the FIRAuthErrorCodeUserTokenExpired error.



    I tried it in didFinishLaunchingWithOptions() of my iOS App. The data is read correctly, but there should be an error as I deactivated the test-user account (token should be revoked). Unfortunately, Firebase still handles the request and logs in the user without throwing an error.



    For an app that should be as secure as possible, it is very suboptimal if you stay logged in into the app though you're token has already been revoked.



    Here is my code:



    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
    }


    Here my Firebase Rules:



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


    I am aware that the rules are not perfectly adjusted yet but in my eyes, Firebase should throw an error, as the token is expired. I am aware that I have not yet checked for the correct error but the if let does not get called anyways.



    I checked multiple resources including the Firebase documentation corresponding to this topic but the documentation only covers how to detect revoked tokens in the web and not on iOS or Android.



    Besides that, I checked a stack overflow entry but it had no correct answer that was helpful so I decided to post my own one here:



    Does anyone know the right way how to detect revoked tokens as soon as they occur on iOS?



    I am sorry if this question is not perfectly formulated. I am still new to stack overflow, so please be kind :)










    share|improve this question

























      0












      0








      0


      0






      according to the Google Support, the only way to detect revoked firebase tokens is by making a read-request to my Firestore and catching back the FIRAuthErrorCodeUserTokenExpired error.



      I tried it in didFinishLaunchingWithOptions() of my iOS App. The data is read correctly, but there should be an error as I deactivated the test-user account (token should be revoked). Unfortunately, Firebase still handles the request and logs in the user without throwing an error.



      For an app that should be as secure as possible, it is very suboptimal if you stay logged in into the app though you're token has already been revoked.



      Here is my code:



      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
      }


      Here my Firebase Rules:



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


      I am aware that the rules are not perfectly adjusted yet but in my eyes, Firebase should throw an error, as the token is expired. I am aware that I have not yet checked for the correct error but the if let does not get called anyways.



      I checked multiple resources including the Firebase documentation corresponding to this topic but the documentation only covers how to detect revoked tokens in the web and not on iOS or Android.



      Besides that, I checked a stack overflow entry but it had no correct answer that was helpful so I decided to post my own one here:



      Does anyone know the right way how to detect revoked tokens as soon as they occur on iOS?



      I am sorry if this question is not perfectly formulated. I am still new to stack overflow, so please be kind :)










      share|improve this question














      according to the Google Support, the only way to detect revoked firebase tokens is by making a read-request to my Firestore and catching back the FIRAuthErrorCodeUserTokenExpired error.



      I tried it in didFinishLaunchingWithOptions() of my iOS App. The data is read correctly, but there should be an error as I deactivated the test-user account (token should be revoked). Unfortunately, Firebase still handles the request and logs in the user without throwing an error.



      For an app that should be as secure as possible, it is very suboptimal if you stay logged in into the app though you're token has already been revoked.



      Here is my code:



      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
      }


      Here my Firebase Rules:



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


      I am aware that the rules are not perfectly adjusted yet but in my eyes, Firebase should throw an error, as the token is expired. I am aware that I have not yet checked for the correct error but the if let does not get called anyways.



      I checked multiple resources including the Firebase documentation corresponding to this topic but the documentation only covers how to detect revoked tokens in the web and not on iOS or Android.



      Besides that, I checked a stack overflow entry but it had no correct answer that was helpful so I decided to post my own one here:



      Does anyone know the right way how to detect revoked tokens as soon as they occur on iOS?



      I am sorry if this question is not perfectly formulated. I am still new to stack overflow, so please be kind :)







      ios firebase firebase-authentication google-cloud-firestore firebase-security-rules






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 20 '18 at 17:44









      linus_hologramlinus_hologram

      14




      14
























          1 Answer
          1






          active

          oldest

          votes


















          0














          I found the following solution:



          in didFinishLaunchingWithOptions add the following piece of code:



          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")
          }
          })
          }


          Ah, and don't forget to initialize Firebase before running this code (else you won't have access to Firebase Auth)






          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53398646%2fcheck-for-invalid-user-token-firebase-in-didfinishlaunchingwithoptions%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I found the following solution:



            in didFinishLaunchingWithOptions add the following piece of code:



            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")
            }
            })
            }


            Ah, and don't forget to initialize Firebase before running this code (else you won't have access to Firebase Auth)






            share|improve this answer






























              0














              I found the following solution:



              in didFinishLaunchingWithOptions add the following piece of code:



              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")
              }
              })
              }


              Ah, and don't forget to initialize Firebase before running this code (else you won't have access to Firebase Auth)






              share|improve this answer




























                0












                0








                0







                I found the following solution:



                in didFinishLaunchingWithOptions add the following piece of code:



                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")
                }
                })
                }


                Ah, and don't forget to initialize Firebase before running this code (else you won't have access to Firebase Auth)






                share|improve this answer















                I found the following solution:



                in didFinishLaunchingWithOptions add the following piece of code:



                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")
                }
                })
                }


                Ah, and don't forget to initialize Firebase before running this code (else you won't have access to Firebase Auth)







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Feb 17 at 18:16

























                answered Nov 21 '18 at 21:16









                linus_hologramlinus_hologram

                14




                14
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53398646%2fcheck-for-invalid-user-token-firebase-in-didfinishlaunchingwithoptions%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to send String Array data to Server using php in android

                    Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

                    Is anime1.com a legal site for watching anime?