简体   繁体   English

Firebase REST API - 使用id令牌验证请求不起作用

[英]Firebase REST API - authenticating request with id token doesn't work

I'm working on a Unity C# project and trying to authenticate a request to Realtime Database using the id token Firebase returns after a user signs in, but it says the request is unauthorized. 我正在开发一个Unity C#项目,并尝试使用用户登录后返回的id令牌来验证对Realtime Database的请求,但它表示该请求未经授权。 Here's my sign-in code ( AuthResponse wraps the response body): 这是我的登录代码( AuthResponse包装响应正文):

WWWForm form = new WWWForm();
form.AddField("email", email);
form.AddField("password", password);

using (UnityWebRequest www = UnityWebRequest.Post("https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=" + API_KEY, form))
{
    yield return www.SendWebRequest();

    if (www.isNetworkError || www.isHttpError)
    {
        Debug.Log($"Login failed: {www.error}");
        callback(false);
    }
    else
    {
        AuthResponse data = www.downloadHandler.text.FromJson<AuthResponse>();
        ID_TOKEN = data.idToken;
    }
}

And my read request: 我的阅读要求:

string url = $"{DATABASE_URL}{path}.json";
if (auth) url += $"?auth={ID_TOKEN}";
using (UnityWebRequest www = UnityWebRequest.Get(url))
{
    yield return www.SendWebRequest();

    if (www.isNetworkError || www.isHttpError)
    {
        Debug.Log($"Read failed: {www.error}");
    }
}

My database has public rules and everything works without the auth parameter. 我的数据库有公共规则,一切都没有auth参数。 What am I missing? 我错过了什么?

Edit: This is the token response: 编辑:这是令牌响应:

{
  "kind": "identitytoolkit#SignInWithPasswordResponse",
  "localId": <LOCAL_ID>,
  "email": <EMAIL>,
  "displayName": "",
  "idToken": <ID_TOKEN>,
  "registered": true
}

This is the full read request url: https://<PROJECT_ID>.firebaseio.com/testing/flatString.json?auth=<ID_TOKEN> 这是完整的读取请求URL: https://<PROJECT_ID>.firebaseio.com/testing/flatString.json?auth=<ID_TOKEN>

instead of doing your own httppost use Firebase Unity SDK 而不是使用自己的httppost使用Firebase Unity SDK

Before you can use Firebase Authentication, you need to: 在使用Firebase身份验证之前,您需要:

Register your Unity project and configure it to use Firebase. 注册Unity项目并将其配置为使用Firebase。

If your Unity project already uses Firebase, then it's already registered and configured for Firebase. 如果您的Unity项目已使用Firebase,那么它已经为Firebase注册和配置。

If you don't have a Unity project, you can download a sample app. 如果您没有Unity项目,可以下载示例应用程序。

Add the Firebase Unity SDK (specifically, FirebaseAuth.unitypackage) to your Unity project. 将Firebase Unity SDK(特别是FirebaseAuth.unitypackage)添加到Unity项目中。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM