简体   繁体   English

如何在 Firebase 3.x 中禁用注册

[英]How to disable Signup in Firebase 3.x

I have created some users using firebase.auth().signInWithEmailAndPassword and would like to stop signUp now, but keep signIn working.我已经使用 firebase.auth().signInWithEmailAndPassword 创建了一些用户,现在想停止注册,但保持登录工作。 I tried some rules on users and even to stop writing to firebase at all.我尝试了一些用户规则,甚至完全停止写入 firebase。 However registration was still possible.但是仍然可以注册。 Disabling Email/Password within console disables login too.在控制台中禁用电子邮件/密码也会禁用登录。

{
  "rules": {
        ".read": true,
        ".write": false,
      }
}

Any ideas how to apply security rules to users in Firebase 3?任何想法如何将安全规则应用于 Firebase 3 中的用户?

Firebase explicitly separates authentication (signing in to the app) from authorization (accessing database or storage resources from the app). Firebase 明确将身份验证(登录应用程序)与授权(从应用程序访问数据库或存储资源)分开。

You cannot disable sign-up without disabling sign-in for all users, which is not what you want.您不能在不禁用所有用户登录的情况下禁用注册,这不是您想要的。

In a typical scenario, developer will start securing database/file access based on the authenticated user.在典型的场景中,开发人员将根据经过身份验证的用户开始保护数据库/文件访问。 See the relevant section in the docs for database security andstorage security .有关数据库安全性存储安全,请参阅文档中的相关部分。

If your use-case is that you only want specific users to have access, you'll probably want to implement a whitelist: a list of users that are allowed to access the data.如果您的用例是您只希望特定用户具有访问权限,您可能需要实现一个白名单:允许访问数据的用户列表。

You can do that in your security rules:您可以在安全规则中执行此操作:

{
  "rules": {
        ".read": "auth.uid == '123abc' || auth.uid == 'def456'",
        ".write": false,
      }
}

Or (better) by putting the list of allowed uids in your database and referring to that from your security rules:或者(更好)通过将允许的 uid 列表放在您的数据库中并从您的安全规则中引用该列表:

"allowedUids": {
    "123abc": true,
    "def456": true
}

And then:然后:

{
  "rules": {
        ".read": "root.child('allowedUids').child(auth.uid).exists()",
        ".write": false,
      }
}

Well it's been days since the question was asked but maybe this could help for those who are still wondering for the answer, we still can't simply disable the new account creation but we can do using Firebase functions:好吧,这个问题已经有好几天了,但也许这对那些仍然想知道答案的人有帮助,我们仍然不能简单地禁用新帐户创建,但我们可以使用 Firebase 函数:

Here is the workaround for auto-disable new users using cloud functions.这是使用云功能自动禁用新用户的解决方法。

const functions = require('firebase-functions');
const admin = require('firebase-admin');
    
exports.blockSignup = functions.auth.user().onCreate(event => {
  return admin.auth()
    .updateUser(event.uid, {disabled: true})
    .then(userRecord => console.log(`Auto blocked user: ${userRecord.toJSON()}`))
    .catch(error => console.log(`Error auto blocking: ${error}`));
});

Remembering that this function is fired when you create users using the Firebase web console, or by 3rd parties.请记住,当您使用 Firebase 网络控制台或由 3rd 方创建用户时,会触发此函数。 So you have to create, await the function, then enable the user.所以你必须创建,等待函数,然后启用用户。

If you want to remove the signup option from FirebaseUI in Android app than you have to add the following provider:如果您想从 Android 应用程序的FirebaseUI中删除注册选项,则必须添加以下提供程序:

new AuthUI.IdpConfig.EmailBuilder().setAllowNewAccounts(false).build());

and the function will look like the following:该函数将如下所示:

private void FireBaseLoginUI() {
        List<AuthUI.IdpConfig> providers = Collections.singletonList(
                new AuthUI.IdpConfig.EmailBuilder().setAllowNewAccounts(false).build());

        startActivityForResult(
                AuthUI.getInstance()
                        .createSignInIntentBuilder()
                        .setAvailableProviders(providers)
                        .setLogo(R.drawable.app_logo)
                        .setTheme(R.style.AuthUITheme)
                        .build(),
                RC_SIGN_IN);
}

I use this:我用这个:

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
const admin = require("firebase-admin");

admin.initializeApp();

exports.blockSignup = functions.auth.user().onCreate(event => {
    if (process.env['allowCreation'] === "false")
        return admin.auth().deleteUser(event.uid);
    else return Promise.resolve("letUserCreate");
});

After creating the users I want, go to https://console.cloud.google.com/functions and change the environment variable to false, redeploy, done.创建我想要的用户后,转到https://console.cloud.google.com/functions并将环境变量更改为 false,重新部署,完成。

Alternatively you could add the user to firestore and only allow to sign up if the user exists on firestore.或者,您可以将用户添加到 firestore,并且仅当用户存在于 firestore 时才允许注册。 Like so:像这样:

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
const admin = require("firebase-admin");

admin.initializeApp();

exports.blockSignup = functions.auth.user().onCreate(user => {
    return new Promise((resolve, reject) => {
        admin.firestore().collection('users').doc(user.email).get().then(doc => {
            if (doc.exists) {
                resolve("letUserCreate");
            }
            else {
                reject(admin.auth().deleteUser(user.uid))
            }
        }).catch(reason => {
            console.error(reason)
            reject(admin.auth().deleteUser(user.uid))
        })
    });
});

If you enable the Cloud Identity API then you can disable sign up and delete account actions for users and limit them to the Admin SDK .如果您启用Cloud Identity API,则可以禁用用户的注册和删除帐户操作,并将其限制为Admin SDK

在此处输入图片说明

You can visit https://console.cloud.google.com/customer-identity/settings to disable them.您可以访问https://console.cloud.google.com/customer-identity/settings来禁用它们。

You might get this notice while enabling the API on an existing project:在现有项目上启用 API 时,您可能会收到此通知:

在此处输入图片说明

Once disabled, using the createUserWithEmailAndPassword method returned a 400 error:禁用后,使用createUserWithEmailAndPassword方法返回 400 错误:

{
  "error": {
    "code": 400,
    "message": "ADMIN_ONLY_OPERATION",
    "errors": [
      {
        "message": "ADMIN_ONLY_OPERATION",
        "domain": "global",
        "reason": "invalid"
      }
    ]
  }
}

Do note that you can still use Admin SDK to create new users.请注意,您仍然可以使用 Admin SDK 创建新用户。

The documentation for the same can be found here可以在此处找到相同的文档

As mentioned above, it's important to differentiate between authentication and authorization.如上所述,区分身份验证和授权很重要。 Therefore, this can also be done slightly off of Firebase.因此,这也可以在 Firebase 之外稍微完成。 If you are building a web app for example and you want to allow access to a given page to a specific list of users then you can handle it within your web app.例如,如果您正在构建一个 Web 应用程序,并且您希望允许特定用户列表访问给定页面,那么您可以在您的 Web 应用程序中处理它。

This example is for executing an onCall firebase function.此示例用于执行 onCall firebase 函数。 It only executes if the user UID is 12345仅当用户 UID 为12345时才执行

exports.ILoveConsole = functions.https.onCall((message, context) => {

//message is just a text
//context hold the user auth information

    'use strict';
        if (context && context.auth && context.auth.uid) {
            if(context.auth.uid === "12345"){
                console.log("I love security");
            }
            else{
                console.log("You are authenticated but not authorized");
            }
        }
        else {
            console.log("You are neither authenticated nor authorized");
        }
});

Note: If you want to do a list of users, you can do a for loop function to check the array of your authorized users in browser or call a firebase function.注意:如果你想做一个用户列表,你可以做一个 for 循环函数来检查浏览器中授权用户的数组或调用一个 firebase 函数。 They both should run before loading the page他们都应该在加载页面之前运行

I don't know if Google added this option since the other answers were posted, or if it's just so buried in the documentation that most people don't know about it, but there is a disableSignup option for FirebaseUI Auth.我不知道 Google 是否在发布其他答案后添加了此选项,或者它是否隐藏在大多数人不知道的文档中,但 FirebaseUI Auth 有一个disableSignup选项。 https://github.com/firebase/firebaseui-web/blob/master/README.md#configure-email-provider https://github.com/firebase/firebaseui-web/blob/master/README.md#configure-email-provider

The usage looks something like this:用法如下所示:

var uiConfig = {
    callbacks: {
        signInSuccessWithAuthResult: (authResult, redirectUrl) => {
            // User successfully signed in.
            // Call your success handler.
            handleLoginSuccess(authResult.user)
            .then( () => {
                return true;
            })
            .catch( err => {
                return false;
            });
        },
        signInFailure: (err) => {
            console.error(`[signInFailure] ERROR: ${err.message}`);
        },
        uiShown: () => {
            // The widget is rendered.
            // Hide the loader.
            document.getElementById('loader').style.display = 'none';
        }
    },
    signInSuccessUrl: "/",
    signInOptions: [
        {
            provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
            requireDisplayName: true,
            disableSignUp: {
                status: true,
                adminEmail: 'help@example.com',
                helpLink: 'https://example.com/login-help'
            }
        }
    ]
};

ui.start("#firebaseui-auth-container", uiConfig);

Hope this helps future searchers who end up here.希望这对最终来到这里的未来搜索者有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 firebase 身份验证电子邮件提供商注册中禁止使用一次性电子邮件? - How to disallow disposable email in firebase auth email provider signup? 如何使用google auth区分firebase中的登录和注册用户? - How to differentiate signin and signup user in firebase using google auth? 如何在flutter中使用firebase手机号和密码进行登录注册 - How to make login signup with firebase phone number and password in flutter Firebase 首次登录或注册事件 - Firebase first login or signup events 注册时出现 POST 400 错误 - Vue JS / Firebase - POST 400 error on signup - Vue JS / Firebase 如何在 firebase 身份验证中禁用帐户创建 - How to disable account creation in firebase authentication 注册时更新显示名称 Firebase Flutter - Update displayName while signup Firebase Flutter 如何让 AWS Device Farm 使用 python 3.x 运行 Appium 测试? - How do I make AWS Device Farm run Appium tests with python 3.x? Email 和在 React 应用程序中使用 firebase 的密码注册,用户的显示名称在初始渲染中显示为 null。 我怎样才能解决这个问题? - Email and Password Signup using firebase in a react app , the displayName of the user appears to be null on the initial render. How can I fix this? 为 Android 禁用 firebase crashlytics - Disable firebase crashlytics for Android
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM