Flutter and Firestore does not have user information in request - firebase

Using flutter, I have installed the firebase-auth and firestore packages and am able to both authenticate with firebase auth and make a call into firestore as long as I don't have any rules around the user.
I have a button that calls _handleEmailSignIn and I do get a valid user back (since they are in the Firebase Auth DB)
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
final FirebaseAuth _auth = FirebaseAuth.instance;
void _handleEmailSignIn(String email, String password) async {
try {
FirebaseUser user = await _auth.signInWithEmailAndPassword(
email: email, password: password);
print("Email Signed in " + user.uid); // THIS works
} catch (err) {
print("ERROR CAUGHT: " + err.toString());
}
}
I then have another button that calls this function to attempt to add a record into the testing123 collection.
Future<Null> _helloWorld() async {
try {
await Firestore.instance
.collection('testing123')
.document()
.setData(<String, String>{'message': 'Hello world!'});
print('_initRecord2 DONE');
} catch (err) {
print("ERROR CAUGHT: " + err.toString());
}
}
Now this works as long as I don't have any rules around checking the request user. This works...
service cloud.firestore {
match /databases/{database}/documents {
match /testing123auth/{doc} {
allow read, create
}
}
}
This does not which gives PERMISSION_DENIED: Missing or insufficient permissions. when I want to make sure I have the authenticated user I did with _handleEmailSignIn.
service cloud.firestore {
match /databases/{database}/documents {
match /testing123auth/{doc} {
allow read, create: if request.auth != null;
}
}
}
I suspect that the firestore request is not including the firebase user. Am I meant to configure firestore to include the user or is this supposed to be automatic as part of firebase?

One thing to note that's not well documented is that firebase_core is the "Glue" that connects all the services together and when you're using Firebase Authentication and other Firebase services, you need to make sure you're getting instances from the same firebase core app configuration.
final FirebaseAuth _auth = FirebaseAuth.instance;
This way above should not be used if you're using multiple firebase services.
Instead, you should always get FirebaseAuth from FirebaseAuth.fromApp(app) and use this same configuration to get all other Firebase services.
FirebaseApp app = await FirebaseApp.configure(
name: 'MyProject',
options: FirebaseOptions(
googleAppID: Platform.isAndroid ? 'x:xxxxxxxxxxxx:android:xxxxxxxxx' : 'x:xxxxxxxxxxxxxx:ios:xxxxxxxxxxx',
gcmSenderID: 'xxxxxxxxxxxxx',
apiKey: 'xxxxxxxxxxxxxxxxxxxxxxx',
projectID: 'project-id',
bundleID: 'project-bundle',
),
);
FirebaseAuth _auth = FirebaseAuth.fromApp(app);
Firestore _firestore = Firestore(app: app);
FirebaseStorage _storage = FirebaseStorage(app: app, storageBucket: 'gs://myproject.appspot.com');
This insures that all services are using the same app configuration and Firestore will receive authentication data.

There shouldn't be any special configuration needed for the firestore to do this.
This is all you should need.
Modified from Basic Security Rules:
service cloud.firestore {
match /databases/{database}/documents {
match /testing123/{document=**} {
allow read, write: if request.auth.uid != null;
}
}
}
It seems they check if the uid is null rather than the auth itself. Try this out and see if it works. Also, it seemed that your code was inconsistent as the firestore rule had testing123auth and flutter had testing123. I'm not sure if that was intentional.

to check if the user is signed in you should use
request.auth.uid != null

I would have suggested to make the rule like:
service cloud.firestore {
match /databases/{database}/documents {
match /testing123auth/{documents=**} {
allow read, create: if true;
}
}
}
Or, better yet, limit the scope of the user:
service cloud.firestore {
match /databases/{database}/documents {
match /testing123auth/{userId} {
allow read, create:
if (request.auth.uid != null &&
request.auth.uid == userId); // DOCUMENT ID == USERID
} // END RULES FOR USERID DOC
// IF YOU PLAN TO PUT SUBCOLLECTIONS INSIDE DOCUMENT:
match /{documents=**} {
// ALL DOCUMENTS/COLLECTIONS INSIDE THE DOCUMENT
allow read, write:
if (request.auth.uid != null &&
request.auth.uid == userId);
} // END DOCUMENTS=**
} // END USERID DOCUMENT
}
}

Related

Firebase Storage Exception when fetching downloadUrl [Flutter]

When trying to use FireBase Cloud Storage to get a video downloadUrl
final storage = FirebaseStorage.instance;
downloadUrl() async {
final downloadUrl =
await storage.ref("User_uploadVideo/videoplayback.mp4").getDownloadURL();
return downloadUrl;
}
An exception is thrown saying Exception: [firebase_storage/unauthenticated] User is unauthenticated. Authenticate and try again.
Even tho I have opened the security rules to public for development.
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
Try this:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if true;
}
}
}
main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
...
Also, make sure to have AppCheck disabled.

Unhandled Exception: PlatformException(Error performing get, PERMISSION_DENIED: Missing or insufficient permissions., null)

Whenever the app starts this error comes. i think the error mainly is in the saveUserInfoFirestore function.. i saw that many other people have this same problem cause of their firestore security rules but i tried differenct rules it still shows same error..
final GoogleSignIn gSignIn = GoogleSignIn();
final userReference = Firestore.instance.collection("Users");
void initState(){
super.initState();
pageController=PageController();
gSignIn.onCurrentUserChanged.listen((gSigninAccount) { ControlSingIn(gSigninAccount); },
onError: (gError){
print("Google signin error"+ gError);
});
gSignIn.signInSilently(suppressErrors: false).then((gSigninAccount) { ControlSingIn(gSigninAccount); }).
catchError((onError){
print("Signin silently error"+ onError);
});
}
ControlSingIn(GoogleSignInAccount signInAccount) async{
if(signInAccount != null){
await saveUserInfotoFirestore();
setState(() {
isSignin = true;
});
}else{
setState(() {
isSignin = false;
});
}
}
saveUserInfotoFirestore() async{
final GoogleSignInAccount gCurrentuser = gSignIn.currentUser;
DocumentSnapshot documentSnapshot = await userReference.document(gCurrentuser.id).get();
if(!documentSnapshot.exists){
final username = await Navigator.push(context, MaterialPageRoute(builder: (context)=>CreateAccountPage()));
userReference.document(gCurrentuser.id).setData({
"id": gCurrentuser.id,
"profileName": gCurrentuser.displayName,
"username": username,
"url": gCurrentuser.photoUrl,
"email": gCurrentuser.email,
"bio": "",
"timestamp":timestamp
});
documentSnapshot = await userReference.document(gCurrentuser.id).get();
}
currentUser = User.fromDocument(documentSnapshot);
}
heres the firestore security rule that i am using:
rules_version = '2';
// Allow read/write access on all documents to any user signed in to the application
service cloud.firestore {
match /databases/{database}/documents {
match /messages/{document=**} {
allow read, write: if true;
}
}
}
Your security rules only allow access to a single collection called "messages" using this match:
match /messages/{document=**} {
allow read, write: if true;
}
However, your code is trying to write a different collection called "Users". You are seeing a permission error because your rules don't allow any access at all to that collection. You will have to write another rule to allow enough access to that collection as well.
I strongly suggest fully reviewing the documentation for security rules to understand how best to protect your app.
check with your googleservices.json file if it is in the right location. It should be in your project>android folder> app folder>

Flutter - Your Cloud Firestore database has insecure rules

I have a collection called users where I am checking if new users mobile no is present or not. If It is present then I am performing phone authentication for that user then storing uid as a field in document.
If user is coming for the first time, he is not authenticated and I am performing read operation from users collection. Now every time I am getting Your Cloud Firestore database has insecure rules email from google.
Below is the rule I am using. Please let me know how can I make it secure.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read: if true;
allow write: if request.auth != null;
}
}
}
You can change your rule adding more security like this:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
But, then your app won't be able to read from Firebase, since you are telling that even for read is necessary to be authenticated.
I solved this allowing users to authenticate anonymously in Firebase. For this go to:
https://console.firebase.google.com/project/[YOUR-PROJECT]/authentication/providers
and enable Anonymous method. Remember to change [YOUR-PROJECT] in the URL.
After this you will only need to add few lines of code in your main screen or whatever you want.
1) Import the Firebase Auth package:
import 'package:firebase_auth/firebase_auth.dart';
2) Add the following code at the beginning of your main StatefulWidget:
final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
Future<FirebaseUser> signInAnon() async {
AuthResult result = await firebaseAuth.signInAnonymously();
FirebaseUser user = result.user;
print("Signed in: ${user.uid}");
return user;
}
void signOut() {
firebaseAuth.signOut();
print('Signed Out!');
}
3) And now you just have to call the function inside your initState:
signInAnon().then((FirebaseUser user){
print('Login success!');
print('UID: ' + user.uid);
});
And voilá! Now every user user will authenticate anonymously automatically in your Firebase database. The best part is the user persists in the app until you uninstall it or delete the cache data.
Here is a video explaining the steps, but using a login screen which I removed for my project and this example: https://www.youtube.com/watch?v=JYCNvWKF7vw

Firestore Permission denied. Connecting firestore to react native

addPost = async ({ text, localUri }) => {
const remoteUri = await this.uploadPhotoAsync(localUri);
return new Promise((res, rej) => {
this.firestore
.collection("posts")
.add({
text,
uid: this.uid,
timestamp: this.timestamp,
image: remoteUri
})
.then(ref => {
res(ref);
})
.catch(error => {
rej(error);
});
});
};
And
rules_version = '2';
service firebase.storage {
match /posts/{doc} {
allow read, write: if true;
}
}
Above is my react-native code and below it is the firebase rules for my database so far. Still getting
FirebaseError:[code=permission-denied]: Missing or insufficient permissions.
Any help as to how to fix this code or to make my rules more secure? At this point in the code the user has been authenticated.
The rules in the question are for firebase storage, you need to change the rule for firestore to true:
// Allow read/write access to all users under any conditions
// Warning: **NEVER** use this rule set in production; it allows
// anyone to overwrite your entire database.
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
Check here for more information:
https://firebase.google.com/docs/firestore/security/insecure-rules

Firestore permission denied when using signInWithCredential(), React Native Expo

firebase.initializeApp(config);
const db = firebase.firestore();
const googleSignIn = async () => {
return await Expo.Google.logInAsync({
androidClientId,
iosClientId,
scopes: ['profile', 'email'],
});
};
const firebaseLogin = async (accessToken) => {
const cred = firebase.auth.GoogleAuthProvider.credential(null, accessToken);
await firebase.auth().signInWithCredential(cred).catch(console.error);
const idToken = await firebase.auth().currentUser.getIdToken(true).catch(console.error);
};
await firebaseLogin(googleSignIn().accessToken);
db.collection("any").doc().set({test: "OK"})
I get a permission denied error when trying to write to Firestore using a request.auth.uid != null; security rule, but when I replace it with true it works.
It seems that the Firestore component of the web SDK does not send authentication details, even though the API on the client reports Firebase is logged in, and the user last login date appears in the web GUI.
Do I need to pass authentication details to the Firestore component when logging in directly with Google (instead of using the Firebase login APIs)?
The code is running in a React Native app via Expo.
Another example that gets a permission denied:
firebase.auth().onAuthStateChanged((user) => {
if (user) {
firebase.firestore().collection("any").doc().set({test: "OK"});
}
});
Rules
// This is OK:
service cloud.firestore {
match /databases/{database}/documents {
match /any/{doc} {
allow read, write: if true;
}
}
}
// Permission denied
service cloud.firestore {
match /databases/{database}/documents {
match /any/{doc} {
allow read, write: if request.auth.uid != null;
}
}
}
Related
Firebase Firestore missing or insufficient permissions using Expo (React Native)
https://forums.expo.io/t/firestore-with-firebase-auth-permissions-to-read-write-only-to-signed-in-users/5705
This solution, and possibly this whole issue, may be specific to React Native.
In a similar question, Jade Koskela noticed that requests were missing the Origin header, and applies a patch to React's XHRInterceptor to work around the missing auth object:
const xhrInterceptor = require('react-native/Libraries/Network/XHRInterceptor');
xhrInterceptor.setSendCallback((data, xhr) => {
if(xhr._method === 'POST') {
// WHATWG specifies opaque origin as anything other than a uri tuple. It serializes to the string 'null'.
// https://html.spec.whatwg.org/multipage/origin.html
xhr.setRequestHeader('Origin', 'null');
}
});
xhrInterceptor.enableInterception();

Resources