【问题标题】:Firebase custom token vs service accountFirebase 自定义令牌与服务帐户
【发布时间】:2016-11-10 00:28:14
【问题描述】:

我们有带有本地用户列表的安卓应用。该应用在 Firebase 中有一个专用用户(其他用户在本地管理),应该用于访问实时数据库。 UID 将用于应用安全规则并限制对特定数据元素的访问。我认为我们有两个选择:自定义令牌或服务帐户(使用 databaseAuthVariableOverride)。

我想知道使用服务帐户方法可能会遇到哪些安全问题?它是否获得完全访问权限?也许我们可以将其限制为最小的操作集?

自定义令牌方法可能存在令牌过期问题。有没有办法显着延长令牌的有效性?在 android 上生成自定义令牌的最佳方法是什么?

【问题讨论】:

    标签: android firebase firebase-realtime-database firebase-authentication firebase-security


    【解决方案1】:

    使用服务帐户,您可以对所有已安装的应用程序对数据库的访问进行硬编码,换句话说,安装您的应用程序的每个人都会看到完全相同的内容。

    您通常会使用令牌方法,以便为不同的用户定制对数据库上不同节点的访问。这通常通过为您的节点设置一些简单的规则来实现,例如:

        // Sample firebase rules
        {
          "rules": {
            "messages": {
              // Only admin servers with service accounts should r/w here
              ".read": "auth.uid == 'server-with-svc-acct'",
              ".write": "auth.uid == 'server-with-svc-acct'",
              "$user_id": {
                 // Users can only read their own nodes
                 ".read": "auth.uid == $user_id",
                 ".write": "auth.uid ==  $user_id",
    
              }
            }
          }
        }
    

    您可以在official documentation 中查看有关如何使用 Google+ 进行身份验证的详细信息,但一般而言,一旦您进行身份验证,您可以获得一个唯一的用户 ID,然后写入实时数据库上所需的节点。用户将无法访问任何其他节点,因为规则会限制他:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth){
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
            // ...
        }
    };
    // ... 
    

    对于您的服务器,可以安全地保存您的服务帐户机密,您可以通过以下方式启动 Firebase 连接(注意 databaseAuthVariableOverride ?,它与我们在 @ 的根目录上使用的 auth.uid 匹配987654327@ 节点)。

    firebase.initializeApp({
      serviceAccount: "path/to/project-name-secrets.json",
      databaseURL: "https://project-name.firebaseio.com",
      databaseAuthVariableOverride: {
        uid: "server-with-svc-acct"
      }
    });
    

    也可以在documentation 中找到有关此的更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-15
      • 2017-04-25
      • 2019-11-02
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2017-04-16
      • 2019-06-01
      相关资源
      最近更新 更多