![](/img/trans.png)
[英]VueJS + VueFire - Add data to Firebase Real Time Database with authentication
[英]Add Google authentication to Firebase Real Time Database
我正在使用Firebase實時數據庫,我需要為其添加用戶身份驗證。 用戶只能使用Google作為提供商登錄。
當前數據庫模式:
{
"rules": {
".read": true,
".write": true
}
}
新模式應該是這樣的:
// These rules grant access to a node matching the authenticated
// user's ID from the Firebase auth token
{
"rules": {
"users": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}
在我的情況下,我應該使用什么來進行身份驗證? userID ,Google providerID或此處描述的令牌 ?
這是沒有身份驗證的功能來存儲數據:
createMeetup ({commit, getters}, payload) {
console.log('index.js -> createMeetup')
const meetup = {
title: payload.title,
}
let imageUrl
let key
firebase.database().ref('meetups').push(meetup)
.then((data) => {
key = data.key
return key
})
.then(() => {
commit('createMeetup', {
...meetup,
imageUrl: imageUrl,
id: key
})
})
.catch((error) => {
console.log(error)
})
},
您可以允許用戶使用多種方法登錄/驗證。 然后,您可以將它們合並到一個帳戶,如下所述:
https://firebase.google.com/docs/auth/web/account-linking
所以真的可歸結為兩種選擇:
您選擇的任何選項都可以幫助您確定要使用的ID。
對於您的用例,您似乎需要整理幾個步驟。 我猜你的應用程序已經可以連接/使用Firebase,但這些本質上是:
第1步 - 連接
按照慣例使用API密鑰/配置連接到Firebase,應如下所示。
firebase.initializeApp(config)
另請參閱: https : //firebase.google.com/docs/web/setup
你可能已經有了這個地方。 這不會改變,但如果您按照描述應用規則,您的用戶將無法在連接后使用Firebase。
第2步 - 驗證
這基本上告訴Firebase誰已連接。 必須使用Firebase可以驗證的令牌/方法來完成此操作。 使用Google ID是最常用的方法。
使用現有的Google ID /用戶登錄信息
// Initialize a generate OAuth provider with a `google.com` providerId.
var provider = new firebase.auth.OAuthProvider('google.com');
var credential = provider.credential(googleUser.getAuthResponse().id_token);
firebase.auth().signInWithCredential(credential)
另請參閱: https : //firebase.google.com/docs/reference/js/firebase.auth.OAuthProvider#credential
或者讓Firebase SDK執行登錄流程
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
})
另請參閱: https : //firebase.google.com/docs/auth/web/google-signin
最后一個選項是您引用的文檔的首選/建議。
如果如您所述,用戶已經可以使用Google登錄您的應用以獲取其他功能,那么您應該已經在某處擁有了登錄流程。 根據您的具體情況,最好讓Firebase SDK /庫接管此過程,以簡化您的應用程序。
第3步 - 使用數據庫
最后,在對用戶進行身份驗證並應用您建議的規則之后,您還需要確保您編寫的路徑位於當前用戶可訪問的路徑之內。 您可以將其放在一個簡單的功能中,以使其更容易。
const getUserRef = (ref) => {
const user = firebase.auth().currentUser;
return firebase.database().ref(`/users/${user.uid}/${ref}/`);
}
當然,每次要獲取數據庫引用時都不應該檢索當前用戶,但我認為這清楚地說明了需要采取的步驟。
您問題中的auth規則僅表明用戶可以讀/寫他們自己的(可能是)用戶數據。
我假設您正在尋找一種解決方案來授權用戶創建聚合數據,您應該創建類似於此的規則:
這些規則允許登錄的任何用戶創建聚會
{
"rules": {
"meetups": {
"$meetupId": {
".read": "auth.uid != null",
".write": "auth.uid != null"
}
}
}
}
將新的聚會數據推送到數據庫的代碼片段將自動嘗試成功或失敗,具體取決於用戶是否已登錄。 您無需專門告知Firebase用戶登錄的方式.Firebase SDK將為您處理身份驗證。
但是,如果您確實希望根據用戶通過身份驗證的登錄類型提供不同的機制,則可以在規則中進行檢查。 例如,如果您想確保用戶不僅僅是“匿名”登錄。
請參閱文檔: https : //firebase.google.com/docs/database/security/user-security#section-variable
您可以在那里獲得文檔: 使用JavaScript使用Google登錄進行身份驗證 。
您可以通過將Google登錄集成到您的應用中,讓您的用戶使用其Google帳戶對Firebase進行身份驗證。 您可以使用Firebase SDK執行登錄流程,也可以手動執行Google登錄流程並將生成的ID令牌傳遞給Firebase,從而集成Google登錄。
在你開始之前:
要使用Firebase JavaScript SDK處理登錄流程,請按以下步驟操作:
創建Google提供程序對象的實例:
var provider = new firebase.auth.GoogleAuthProvider();
可選:指定要從身份驗證提供程序請求的其他OAuth 2.0范圍。 要添加范圍,請調用addScope()
。
例如:
provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
請參閱身份驗證提供程序文 可選:要將提供程序的OAuth流本地化為用戶首選語言而不顯式傳遞相關的自定義OAuth參數,請在啟動OAuth流之前更新Auth實例上的語言代碼。
例如:
firebase.auth().languageCode = 'pt';
// To apply the default browser preference instead of explicitly setting it.
// firebase.auth().useDeviceLanguage();
可選:指定要與OAuth請求一起發送的其他自定義OAuth提供程序參數。 要添加自定義參數,請使用包含OAuth提供程序文檔和相應值指定的密鑰的對象在初始化的提供程序上調用setCustomParameters。
例如:
provider.setCustomParameters({
'login_hint': 'user@example.com'
});
保留所需的OAuth參數是不允許的,將被忽略。 有關詳細信息,請參閱身份驗證提供程序 使用Google提供程序對象使用Firebase進行身份驗證。 您可以通過打開彈出窗口或重定向到登錄頁面來提示用戶使用其Google帳戶登錄。 重定向方法在移動設備上是首選方法。
要使用彈出窗口登錄,請調用signInWithPopup:
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
另請注意,您可以檢索Google提供商的OAuth令牌,該令牌可用於使用Google API獲取其他數據。 這也是您可以捕獲和處理錯誤的地方。 有關錯誤代碼列表,請查看Auth Reference Docs。
要通過重定向到登錄頁面來登錄,請調用signInWithRedirect:
firebase.auth().signInWithRedirect(provider);
然后,您還可以在頁面加載時調用getRedirectResult()
來檢索Google提供商的OAuth令牌:
firebase.auth().getRedirectResult().then(function(result) {
if (result.credential) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// ...
}
// The signed-in user info.
var user = result.user;
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.