2013-07-12 126 views
31

有沒有一種方法可以作爲Firebase的管理員對Firebase進行身份驗證,以便對其進行完整的讀/寫訪問(已具有保護其部分內容的安全規則),還是必須編寫安全規則以某種方式允許我訪問完整的Firebase,例如通過提供特定的密碼/密鑰。Firebase以管理員身份進行身份驗證

有沒有這樣做的標準或建議的方式?

回答

1

See this for the 'latest' documentation.

authWithCustomToken現在是signInWithCustomToken(火力版本3)

實施例從文檔:

firebase.auth().signInWithCustomToken(token).catch(function(error) { 
    // Handle Errors here. 
    var errorCode = error.code; 
    var errorMessage = error.message; 
    if (errorCode === 'auth/invalid-custom-token') { 
     alert('The token you provided is not valid.'); 
    } else { 
     console.error(error); 
    } 
}); 
+0

嗨,我看到這是連接到firebase的常規auth java,ios js等)。我如何在Python中執行此操作(我的意思是我如何以管理員身份登錄)。我怎樣才能確保誰使用我的管理程序是一個真正的管理員? – Tomer

17

是的。您只需使用Firebase祕密進行身份驗證,而不需要身份驗證令牌。即。

firebaseRef.auth(MY_SECRET); 

您可以在Forge的Authentication部分找到Secret。

+8

'AUTH()'現在depricated。請參閱Matt的回答http://stackoverflow.com/a/27413337/978501 – Sridhar

+1

我使用了ref.authWithCustomToken(),但返回的有效內容具有空屬性:auth,expires,token,uid。除了設置爲'custom'的'provider'屬性外。這是什麼原因? – nodebase

+0

@nodebase響應(authData)是Object {auth:null,expires:null,token:「」,uid:null,provider:「custom」}「但它違背規則'」.read「:」auth.admin == true「' –

46

Andrew的答案僅適用於您在客戶端代碼之外進行身份驗證(否則您顯然不應使用MY_SECRET)。由於像我這樣的許多人使用Firebase來避免服務器代碼,因此這裏有一個替代答案。

在大多數firebase應用程序中,除了簡單登錄「auth」對象(僅存儲電子郵件和密碼)外,您可能還有一個「用戶」對象。您可以在「用戶」對象中爲每個$用戶添加一個「isAdmin」或「isModerator」(或任何您想要的)。

然後你的規則是這樣的(假設你的auth.id相匹配的$用戶密鑰):

{ 
    "rules": { 
    "someObject": { 
     ".write": "root.child('Users').child(auth.uid).child('isAdmin').val() == true" 
    } 
    } 
} 
+1

我剛剛開始使用Firebase,我非常喜歡你的建議,但不應該是'child(auth.uid)'?只是好奇......就像我說的,仍在學習:) –

+0

是的@BenjaminSolum你是對的,auth.uid是新的auth.id。 Firebase完全移除了auth.id,該auth.id僅對提供商唯一,並用全球唯一的ID替換。我在答案中更新了它,希望它能作爲一個整體。 – Kyle

+0

有關使用相等運算符的任何建議,即'.val()== true'或'.val()=== true'? –

15

As per the documentation,你需要使用firebaseRef.authWithCustomToken

示例;

firebaseRef.authWithCustomToken(FIREBASE_SECRET, function(error, authData) { 
    if(!error) { 
    // You are authenticated 
    } 
}); 

firebaseRef.auth現在已過時,使用firebaseRef.authWithCustomToken代替。

+0

響應是(authData)Object {auth:null,expires:null,token :「」,uid:null,provider:「custom」}'但它違背規則'「.read」:「auth.admin == true」' –