Firebase 客户端错误 : Custom token corresponds to a different audience

标签 firebase firebase-realtime-database firebase-authentication

我正在使用 Firebase Python AdminSDK 生成自定义 token ,Javascript 客户端使用该 token 登录 Firebase。当 JS 客户端尝试使用自定义 token 进行身份验证时,它会收到错误消息“自定义 token 对应于不同的受众”。

给出的错误代码:'auth/custom-token-mismatch'。

许多关于“受众”不匹配引用分析的谷歌答案。但我正在做一个 Web 项目,而不是 iOS 或 Android,所以我无法使用 Analytics 来管理受众。

我读过的 SO 答案列在下面的末尾。

我捕获了自定义 token 并将其插入到 https://jwt.io/值和实例化/过期时间(相隔一小时)看起来都不错:

jwt.io 上的解码自定义 token :

{
  "claims": {},
  "uid": "<myuniqueID",
  "sub": "firebase-adminsdk-1knpr@firebase-<myproject>.iam.gserviceaccount.com",
  "iss": "firebase-adminsdk-1knpr@firebase-<myproject>.iam.gserviceaccount.com",
  "iat": 1540153710,
  "aud": "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",
  "exp": 1540157310
}

Python 服务器:

def getFirebaseInstance():  # For Firebase Python SDK
  try:
    currentDir_path = os.path.dirname(os.path.realpath(__file__))
    cred = credentials.Certificate(currentDir_path + '/includeFirebaseServiceAccounts/firebase-<myprojectname>-firebase-adminsdk-1knpr-e1244dd261.json')  
    firebaseAdmin = firebase_admin.initialize_app(cred, { 'databaseURL': 'https://<myprojectname>.firebaseio.com', 'databaseAuthVariableOverride': {'uid':'<myuniqueServerID>'}})
    if firebaseAdmin:
      return(firebaseAdmin)
  except:
    raise


def firebaseClientToken(request):
  try:
    uid = "<myuniqueClientID>"  # case sensitive
    additional_claims = { }
    token = auth.create_custom_token(uid,additional_claims)
    return HttpResponse(token)
  except Exception as err:
    return HttpResponse("System error:" + str(err), status=406)

Javascript 客户端:

(
function authClient2Firebase() {
  $.ajax({
    url: "firebaseClientToken/",
    method: "POST",
    success: function(response) { step2(response); },
    error: function(xhr) { alert("There was an error loading a security check.  Have you lost your internet connection?  Detail:" + xhr.responseText); }
  });

  function step2(customToken) {
    try {
      firebase.auth().signInWithCustomToken(customToken).catch(function(error) {
        var errorCode = error.code;
        var errorMessage = error.message;
          alert("There was an error with the secure login. \n\nDetail: " + errorMessage + '\nCode: ' + errorCode);
      });
    }
    catch(err) {
      alert(err);
    }

    console.log("authClient2Firebase.js: Firebase login succeeded!");
  }
}

)();

我在控制台“设置”页面下的项目确实有一个 Web API key ,但我没有看到任何地方使用它。

控制台的“设置”->“用户和权限”页面下只有我一个用户。

控制台“设置”->“服务帐户”页面上只列出了一个服务帐户。我尝试删除该页面上的所有 secret ,生成一个新 secret ,然后生成并安装一个新的蓝色按钮“ secret ”(糟糕的名称,实际上它生成了一个完整的 json 凭证对象)。

这些是控制台“身份验证”->“登录方法”中列出的域:

localhost                      Default
<myproject>.firebaseapp.com    Default
127.0.0.1                      Custom
auth.firebase.com              Custom

我实际使用的域名是localhost:8000,这里不能输入。

SO 咨询失败的答案:

The custom token corresponds to a different audience (I'm not using a key, except what's stored in the ServiceAccount credentials.)

Firebase token error, "The custom token corresponds to a different audience."

Firebase custom auth issue token different audienceenter link description here (Close, but I'm not using a Node server and not sure what he means by server "must belong to the same project" since the Python server isn't registered in any way except through the ServiceAccount credentials which I downloaded.)

最佳答案

令人尴尬但事实证明,这只是一个简单的疏忽。当 JS 客户端将自身初始化为 Firebase 应用程序时,在进行身份验证之前,它使用的是来自测试环境的旧凭据。

  // Initialize Firebase
  var config = {
    apiKey: "<WebAPI from Firebase console, 'Project Settings'>",
    authDomain: "<myproject>.firebaseapp.com",
    databaseURL: "https://<myproject>.firebaseio.com",
    projectId: "<myproject>",
    storageBucket: "<myproject>.appspot.com",
    messagingSenderId: "<id from Console Project Settings>"  // optional
  };

  firebase.initializeApp(config);

关于Firebase 客户端错误 : Custom token corresponds to a different audience,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52920116/

相关文章:

使用 Firebase 的 iOS 推送通知

firebase - 访问 HackerNews API

javascript - Firebase 登录并使用 google 弹出窗口加载时间过长

javascript - firestore 添加数据两次并且不让我拥有 UID

java - 如何使用查询结果显示 toast 消息并在 Firebase Firestore 中创建新用户?

Firebase 实时数据库规则 : Validation is cascading to child. 如何忽略父节点上的 .validate?

java - 从 Firebase 中删除共享同一个子项的多个数据 - Java - orderByKey

Android - 对 recyclerview (Firebase) 的多个查询

javascript - 如何在 VueJS 3 中使用 9.0.1 Firebase 方法

javascript - 如何在 nextJS getserversideprops 中使用 firebase