Home > front end >  How to apply firebase database security rules from swift code
How to apply firebase database security rules from swift code

Time:11-25

I have added firebase security rules with authentication turned on. i have given write access based on key..

enter image description here

Firebase rules templet

{
  "rules": {
    "users": {
        ".write": "auth.uid == \"jack\""
    }
  }
}

Now i am looking toward adding that rules in swift code

  var ref: DatabaseReference!
  ref = Database.database().reference()

Setting data as

ref.child("users/jack").setValue("jack")..// Something here to change.

CodePudding user response:

You can't set the user's UID from your Swift code. After all, if you could do that, anyone could do it by taking your configuration data and running whatever code they want against your database too.

The only way to set the UID for a user is if you create a custom authentication provider, which can only be done from a trusted environment such as your development machine, a server you control, or Cloud Functions.


To secure your database instead, sign in to Firebase Authentication in your Swift code (for example with anonymous authentication), then log the UID, and use that instead of jack in your security rules.

CodePudding user response:

As per suggestion of Frank.

I have done it as

pod 'Firebase/Auth'

 import FirebaseAuth

   Auth.auth().signInAnonymously { authDataResult, errorObj in
   if let error = errorObj {
          print("Sign in failed:", error.localizedDescription)
   } else {
     guard let userIdRecieved = authDataResult?.user.uid else {return}
            ref.child("users/\(userIdRecieved)/...
                    
                
  • Related