2017-10-05 28 views
1

我是一名學生開發人員,嘗試使用我的角度應用程序中的新Firestore並卡住了安全規則。angular + firestore:如何允許公衆讀取文檔

我想要實現:

顯示使用模板結合的角度視圖一個公司的FireStore文件。該文檔應該可以查看未經認證的用戶。

問題:

如果非認證的用戶試圖查看的頁面權限錯誤

發生:

ERROR Error: Missing or insufficient permissions. at new FirestoreError (error.js:164)

模板文件:

<p>{{ (item | async)?.name }}</p> 

的組件。 ts文件:

interface Profile { 
    name: string; 
} 
... 
private itemDoc: AngularFirestoreDocument<Profile>; 
item: Observable<Profile>; 
... 
ngOnInit() { 

    this.itemDoc = this.afs.doc<Profile>('profiles/0mlC8uWaKeArzk0sfIfX'); 
    this.item = this.itemDoc.valueChanges(); 
} 

公司的FireStore規則:

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

回答

4

如你所知,訪問您的雲計算公司的FireStore數據由Security Rules控制。當您收到「權限不足錯誤」時,表示您的讀取或寫入已被規則拒絕。

你的情況,你有這些規則:

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

大致翻譯成英文,這些說「讓閱讀或只要在數據庫中寫入任何文件作爲用戶登錄」。

因此,如果您收到錯誤,則表示用戶未登錄(request.auth == null)。

所以,你有兩個選擇:

選項1:添加驗證您的應用

您可以添加Firebase Authentication到您的應用程序。這將滿足您的規則最簡單的事情將是匿名身份驗證:

firebase.auth().signInAnonymously() 
.then(function() { 
    // You're signed in, reads will work 
}) 
.catch(function(error) { 
    // Handle Errors here. 
    // ... 
}); 

選項2:改變你的安全規則

如果您希望所有用戶都能夠讀取所有的數據在你的應用程序,你可以打開規則如下:

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

謝謝!我沒有閱讀正確的規則 –

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