我在使用云功能和 firestore 规则时遇到了一些问题。 我想在 Firestore 上使用具有有限权限的云功能并提供 仅具有安全规则中定义的访问权限
它在 RTDB 上没有问题,但在 Firestore 上没有问题。
我试过这个规则
service cloud.firestore {
match /databases/{database}/documents {
match /init/{ID=**} {
allow read, write: if true;
}
match /test/{ID=**} {
allow read, write: if false;
}
}
}
还有这个
const admin = require('firebase-admin');
const functions = require('firebase-functions');
const FieldValue = require('firebase-admin').firestore.FieldValue;
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://******.firebaseio.com',
databaseAuthVariableOverride: {
uid: 'my-worker',
},
});
const db = admin.firestore();
exports.onTestRights = functions.firestore
.document('init/{initID}')
.onCreate((event) => {
const initID = event.params.initID;
return db.collection('test').doc(initID).set({'random key': 'random value'}).then(()=>{
console.log('working');
return;
}).catch((err) =>{
console.log('error: ', err);
return;
});
});
但它仍然在写,而它应该是“权限被拒绝”
有人知道它在 firestore 上是否正常(或尚未植入)或者我误解了什么?
编辑:
当然,我的最终目标不是使用此规则,而是仅使用 (allow read, write: if request.auth.uid == 'my-worker';
)
编辑2: 如果在过程中没有变化,我想使用安全规则像事务一样检查 using this model
最佳答案
如您所见,databaseAuthVariableOverride
仅适用于实时数据库。目前没有任何东西可以让您在 Admin SDK 中对 Firestore 执行相同的操作。
如果您想限制服务器代码的访问权限,您可以使用的一种解决方法是使用 Client JS SDK 而不是 Firebase Admin,并使用自定义 token 登录用户。这是执行此操作的示例代码:
// Configure Firebase Client SDK.
const firebase = require('firebase/app');
require('firebase/auth');
require('firebase/firestore');
firebase.initializeApp({
// ... Initialization settings for web apps. You get this from your Firebase console > Add Firebase to your web app
});
// Configure Firebase Admin SDK.
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
// Create Custom Auth token for 'my-worker'.
const firebaseReady = admin.auth().createCustomToken('my-worker').then(token => {
// Sign in the Client SDK as 'my-worker'
return firebase.auth().signInWithCustomToken(token).then(user => {
console.log('User now signed-in! uid:', user.uid);
return firebase.firestore();
});
});
// Now firebaseReady gives you a Promise that completes with a authorized firestore instance. Use it like this:
exports.onTestRights = functions.firestore
.document('init/{initID}')
.onCreate(event => {
const initID = event.params.initID;
return firebaseReady.then(db => db.collection('test').doc(initID).set({'random key': 'random value'}).then(() => {
console.log('working');
return;
}).catch((err) =>{
console.log('error: ', err);
return;
});
);
});
关于javascript - 如何在 Firestore 上使用具有有限权限的 Admin SDK?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47079664/