Firebase - how to restrict authenticated user's access to certain paths? - javascript

Simple enough question:
How do I restrict paths, such as...
/orders/<userid>
/cart/<userid>
/transactions/<userid>/txid
...only to users whose userid matches the one in the path?
I have authentication set up and I need to subscribe to some of these in Vue after firebase.auth().onAuthStateChanged
It appears, as per the docs here, that in the following rule example, the user token must match the key exactly:
{
"rules": {
"users": {
"$user_id": {
// grants write access to the owner of this user account
// whose uid must exactly match the key ($user_id)
".write": "$user_id === auth.uid"
}
}
}
}
Does this mean that, /orders/123456/order123478 will be restricted and only available to user 123456?

For the realtime database, update your rules to something like this:
{
"rules": {
"orders": {
"$uid": {
".read": "auth.uid == $uid",
".write": "auth.uid == $uid"
}
}
}
}
The $uid key represents any key nested at that level and allows you to reference it in your rules. The auth variable is provided by Firebase and contains details about the authenticated user who issued the request, so you can compare the requesting user's uid with the database's uid key and grant permissions if they match (the nested ".read" and ".write" values).
So for a user who's uid is user1, they would have access to the following data:
{
"orders": {
"user1": {
"order1": read/write,
"order2": read/write
},
"user2": {
"order1": no access,
"order2": no access
},
"user3": {
"order1": no access,
"order2": no access
},
}
Read the documentation and play around with the simulator found in the Rules section of the Firebase dashboard.

Related

How to pass Auth token in FireStore in Web app

I have developed a single crud project(Login screen and crud operation screen HTML) and hosted on firebase hosting. where User signing with email and password, I am using firebase signing with email and password and its working as expected.
But now issue is I want to secure backend with auth but its not passing auth in setDoc() deleteDoc() etc, My requirement is without auth. no one should do any operation on database.
import { doc, setDoc } from "firebase/firestore";
await setDoc(doc(db, "cities", "LA"), {
name: "Los Angeles",
state: "CA",
country: "USA"
});
below rules are working but its not secured for production env. :
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true
}
}
}
If set rules like below it give me insufficient permission error. I don't know how to pass UID in setDoc() or any operation.
allow read, write: if request.auth != null
Update : If i put below code before setDoc() below code is not executing because currentUser has user data.
function addCity(){
if (!firebase.auth().currentUser) {
// this code not executing because user is signed
alert("Login required");
window.href = "login.html";
return;
}
// i can print UID and it is showing means user is logged.
await setDoc(doc(db, "cities", "LA"), {
name: "Los Angeles",
state: "CA",
country: "USA"
});
}
This is in detail covered in the Firebase documentation on Security & Rules, which I would recommend you to check out.You can secure your data with Security Rules,Firebase Security Rules are evaluated and based on that the rules language it is validated whether the current user can access your data.
Security Rules give you access to a set of server variables to check your rules against. The most commonly used one is the auth variable which lets you check against the currently authenticated user. You can also create wildcard variables with the $, which acts as a route parameter creating.
{ "rules": { "users": { // users can read and write their own data, but no one else. "$uid": { ".read": "auth.uid == $uid", ".write": "auth.uid == $uid" } } } }
You can also check the feature called Firebase App Check, it will let you limit access to your Realtime Database to only those coming from iOS, Android and Web apps that are registered in your Firebase project.
You can combine this with the user authentication based security described above, so that you have another shield.
Also check these similar examples below:
How to prevent unauthorized access to Firebase database
How to prevent users from changing the Database data
Allow only authenticated users to modify database data
Finally,
I found solution. I was using different version library of firebase. like I was using web v8 library for login and modular lib for database access. I just moved all firebase SDK to same version and modular.

Compare requesting users uid to admins uid

So I'm trying to write some firebase rules for my realtime database.
I want my admin to be the only person/account that can edit an object in my database.
I've so far tried:
"Calender": {
".read": true,
"$user_id": {
".write": "$user_id === 'admins uid here, copied from firebase console'",
}
}
But as soon as I "set" to the database, I get the following warning, even if I'm logged in as the admin:
FIREBASE WARNING: set at /Calender failed: permission_denied
How do I compare if the user is an admin based on the requesting users uid?

How to improve firebase real time database rules with anonymous user

I have a simple json tree like this : https://ibb.co/Rgpznd0, and my rules are:
{
"rules": {
".read": "auth.uid !== null",
".write": "false",
}
}
I only need to read the data from the database, i retrieve the token from the user
const accessToken = await user.getIdToken();
and i do a get request with this url with axios:
https://discover-planets-to-visit-default-rtdb.europe-west1.firebasedatabase.app/${query}.json?auth=${accessToken}
this work, but i get some warning from firebase about security rules
///////////////////////////////
UPDATE
I tried to put the rules like this, in a more secure way :
{
"rules": {
"destinations": {
"$uid": {
".read": "auth != null && auth.uid == $uid",
".write": "false"
}
}
}
}
I tried changing the url like this:
https://discover-planets-to-visit-default-rtdb.europe-west1.firebasedatabase.app/destinations.json/${uid}?auth=${accessToken}
But now the axios request doesn't work even if i put the uid in the query.
I also tried on postman and the response it's seems the html of the page, I am doing something wrong.
How can i do that? And get a json response?
////////////
UPDATE 2
full url like requested
https://discover-planets-to-visit-default-rtdb.europe-west1.firebasedatabase.app/destinations.json/nQhLc86TWHeHhSP7JSuPAJdBKyk1?auth=${accessToken}
UPDATE 3
I have find a solution to my problem, you can check the answer below
I follow this guide: https://medium.com/#skytreasure/easy-way-to-secure-firebase-realtime-database-with-rules-when-you-have-anonymous-sign-in-or-already-e8ff1ddfbfc9
Inside the onAuthStateChanged i set a request to the database with the secure key
await set(
ref(
db,
`/${process.env.NEXT_PUBLIC_FIREBASE_ROUTE}/${user.uid}`
),
true
)
.then(() => {
//Fullfilled
})
.catch((error: Error) => {
throw new Error(error.message);
});
Then i didn't change the other methods to fetch.
https://discover-planets-to-visit-default-rtdb.europe-west1.firebasedatabase.app/${query}.json?auth=${accessToken}
Instead of query i put: 'destination' - 'crew' - 'technology' depends of witch pages do you go.
Now the database is secure, only who have the anonymous id can do the request

Firebase: authorisation for edit / delete operations without creating an user login

I created an app where anonymous users can write comments. Now I want them also to edit and delete (only) their comments. Is this possible without using firebase auth?
Since it is only a one-time app for the user its kind of an overkill to create a login for each user.
I tried to store an editKey with the comment-object which should allow the user to edit / delete his comment. (I store this key for the user in a cookie in the browser)
Then somehow deny reading the editKey (".read:" false) via firebase rules. Only allow the write operation when the editKey is known: ".write": "data.val() == newData.val()"
"comments" : {
".read": true,
"$comment_id": {
".write": "!data.exists() && newData.exists()",
"text": {
".validate": "newData.isString()"
},
"created": {
".validate": "newData.isNumber()"
},
"editKey": {
".read": false,
".write": "data.val() == newData.val()",
".validate": "newData.isString()"
},
"visible": {
".validate": "newData.isBoolean()"
},
}
}
But this does not work because the whole comment, which should be public, is not readable when I set the rule ".read:" false for the editKey
Any ideas how this could be achieved without firebase.auth() ?
You are looking for Authenticate with Firebase Anonymously
https://firebase.google.com/docs/auth/web/anonymous-auth#authenticate-with-firebase-anonymously
You can use Firebase Authentication to create and use temporary
anonymous accounts to authenticate with Firebase. These temporary
anonymous accounts can be used to allow users who haven't yet signed
up to your app to work with data protected by security rules. If an
anonymous user decides to sign up to your app, you can link their
sign-in credentials to the anonymous account so that they can continue
to work with their protected data in future sessions.

Firebase - Why is it not pulling my information? [duplicate]

I'm relatively new to coding and am having trouble.
I have this code to send data to firebase
app.userid = app.user.uid
var userRef = app.dataInfo.child(app.users);
var useridRef = userRef.child(app.userid);
useridRef.set({
locations: "",
theme: "",
colorScheme: "",
food: ""
});
However, I keep getting the error:
FIREBASE WARNING: set at /users/(GoogleID) failed: permission_denied
2016-05-23 22:52:42.707 firebase.js:227 Uncaught (in promise) Error: PERMISSION_DENIED: Permission denied(…)
When I try to look this up it talks about rules for Firebase, which seems to be in a language that I haven't learned yet (or it is just going over my head). Can someone explain what is causing the issue? I thought it was that I was asking for it to store email and user display name and you just weren't allowed to do this, but when I took those out I still had the same problem. Is there a way to avoid this error without setting the rules, or are rules something I can teach myself how to write in a day, or am I just way out of my league?
Thanks for any help!
By default the database in a project in the Firebase Console is only readable/writeable by administrative users (e.g. in Cloud Functions, or processes that use an Admin SDK). Users of the regular client-side SDKs can't access the database, unless you change the server-side security rules.
You can change the rules so that the database is only readable/writeable by authenticated users:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
See the quickstart for the Firebase Database security rules.
But since you're not signing the user in from your code, the database denies you access to the data. To solve that you will either need to allow unauthenticated access to your database, or sign in the user before accessing the database.
Allow unauthenticated access to your database
The simplest workaround for the moment (until the tutorial gets updated) is to go into the Database panel in the console for you project, select the Rules tab and replace the contents with these rules:
{
"rules": {
".read": true,
".write": true
}
}
This makes your new database readable and writeable by anyone who knows the database's URL. Be sure to secure your database again before you go into production, otherwise somebody is likely to start abusing it.
Sign in the user before accessing the database
For a (slightly) more time-consuming, but more secure, solution, call one of the signIn... methods of Firebase Authentication to ensure the user is signed in before accessing the database. The simplest way to do this is using anonymous authentication:
firebase.auth().signInAnonymously().catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
And then attach your listeners when the sign-in is detected
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var userRef = app.dataInfo.child(app.users);
var useridRef = userRef.child(app.userid);
useridRef.set({
locations: "",
theme: "",
colorScheme: "",
food: ""
});
} else {
// User is signed out.
// ...
}
// ...
});
I was facing similar issue and found out that this error was due to incorrect rules set for read/write operations for real time database. By default google firebase nowadays loads cloud store not real time database. We need to switch to real time and apply the correct rules.
As we can see it says cloud Firestore not real time database, once switched to correct database apply below rules:
{
"rules": {
".read": true,
".write": true
}
}
Note:
Be careful with the rules. By setting read and write to true makes database vulnerable to praying eyes.
Read more:
https://firebase.google.com/docs/database/security
Go to the "Database" option you mentioned.
There on the Blue Header you'll find a dropdown which says Cloud Firestore Beta
Change it to "Realtime database"
Go to Rules and set .write .read both to true
Copied from here.
Go to database, next to title there are 2 options:
Cloud Firestore, Realtime database
Select Realtime database and go to rules
Change rules to true.
OK, but you don`t want to open the whole realtime database!
You need something like this.
{
/* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
"rules": {
".read": "auth.uid !=null",
".write": "auth.uid !=null"
}
}
or
{
"rules": {
"users": {
"$uid": {
".write": "$uid === auth.uid"
}
}
}
}
Open firebase, select database on the left hand side.
Now on the right hand side, select [Realtime database] from the drown and change the rules to:
{
"rules": {
".read": true,
".write": true
}
}
Another solution is to actually create or login the user automatically if you already have the credentials handy. Here is how I do it using Plain JS.
function loginToFirebase(callback)
{
let email = 'xx#xx.com';
let password = 'xxxxxxxxxxxxxx';
let config =
{
apiKey: "xxx",
authDomain: "xxxxx.firebaseapp.com",
projectId: "xxx-xxx",
databaseURL: "https://xxx-xxx.firebaseio.com",
storageBucket: "gs://xx-xx.appspot.com",
};
if (!firebase.apps.length)
{
firebase.initializeApp(config);
}
let database = firebase.database();
let storage = firebase.storage();
loginFirebaseUser(email, password, callback);
}
function loginFirebaseUser(email, password, callback)
{
console.log('Logging in Firebase User');
firebase.auth().signInWithEmailAndPassword(email, password)
.then(function ()
{
if (callback)
{
callback();
}
})
.catch(function(login_error)
{
let loginErrorCode = login_error.code;
let loginErrorMessage = login_error.message;
console.log(loginErrorCode);
console.log(loginErrorMessage);
if (loginErrorCode === 'auth/user-not-found')
{
createFirebaseUser(email, password, callback)
}
});
}
function createFirebaseUser(email, password, callback)
{
console.log('Creating Firebase User');
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function ()
{
if (callback)
{
callback();
}
})
.catch(function(create_error)
{
let createErrorCode = create_error.code;
let createErrorMessage = create_error.message;
console.log(createErrorCode);
console.log(createErrorMessage);
});
}
PermissionDenied can also appear if provided Firebase project ID is incorrect.
See this guide to check your project ID:
Firebase console: Click settings Project settings. The project ID is displayed in the top pane.
If you are attempting to reuse an old project in firebase, due to free account restrictions, then your database rules are probably outdated.
In my case, I was getting error 401 Unauthorized and it solved when I set both read and write rules equal to true.
Thanks for this great community!
Much respect from Brazil!
i was also having the same problem. make sure that you are using the real-time database instead of the cloud. then change rules to allow access to all users as follows
{
"rules": {
".read": true,
".write": true
}
}
by default the firestore database only allows admins to read and write from the database thus the read/write rules will be set to false.

Categories

Resources