簡體   English   中英

如何在 firebase 身份驗證中禁用帳戶創建

[英]How to disable account creation in firebase authentication

我有一個項目,我曾經在其中使用firebase-auth對用戶進行身份驗證。在我的項目中,用戶無法自行創建帳戶。只有管理員有權添加用戶帳戶。

為了使用onAuthStateChanged() function 我必須在我的頁面中使用 firebase firebase-auth 。但問題是因為在客戶端使用firebase-auth可以通過運行createUserWithEmailAndPassword() function 在控制台上輕松創建帳戶.

現在如何限制人們在客戶端使用createUserWithEmailAndPassword() function?

阻止客戶端應用程序創建帳戶的唯一方法是在 Firebase 控制台中為您的項目禁用所有身份驗證提供程序。 如果您想立即嘗試將其刪除,您可以編寫一個auth onCreate Cloud Function來嘗試確定新帳戶是由客戶端還是管理員代碼創建的。

我認為您可以在添加用戶后通過需要授權的雲功能添加聲明,以便如果用戶沒有該聲明,他將無法使用該應用程序或無法登錄。

在 2022 年,使用帶有 Identity Platform 和阻塞功能的 Firebase Auth,我們可以通過以下方式完成:

創建一個接收 email、密碼和 displayName 的 HTTP function,並使用 firebase-admin 創建用戶:

 import { https } from 'firebase-functions'; import { getAuth } from 'firebase-admin/auth'; import cors from 'cors'; const auth = getAuth(); // Register an HTTP function with the Functions Framework export const signupUser = https.onRequest((req, res) => { const options = { origin: 'http://localhost:3000' }; cors(options)(req, res, () => { console.log('all good'); auth.createUser({ email: 'example@email.com', emailVerified: false, password: 'secretPassword', displayName: 'John Doe', disabled: false, }).then((userRecord) => { // See the UserRecord reference doc for the contents of userRecord. console.log('Successfully created new user:', userRecord.uid); }).catch((error) => { console.log('Error creating new user:', error); }); // Send an HTTP response res.send('OK'); }); });

根據需要修改 CORS 中的響應和原點。

現在創建一個阻塞 beforeCreate function 並檢查用戶的顯示名稱,如果沒有顯示名稱,則拋出錯誤:

 import { auth } from "firebase-functions"; import { initializeApp, applicationDefault } from 'firebase-admin/app'; import { getAuth } from 'firebase-admin/auth'; import postmark from 'postmark'; const app = initializeApp({ credential: applicationDefault(), projectId: 'your_project_id', }); const tnc = getAuth(app); export const signUp = auth.user().beforeCreate((user, context) => { if (.user.displayName) { throw new auth;HttpsError('permission-denied'); } });

這將起作用,因為通過客戶端注冊時無法包含“顯示名稱”

因此,簡而言之,您的重點是創建一個 Cloud Function,它將注冊用戶並確保將檢查添加到 beforeCreate 中,以獲取您知道只能通過 firebase-admin sdk 在服務器端執行的操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM