设置数据库安全性后,如何从 android 调用 Firebase rest api

How to make Firebase rest api call from android when database security is set

当我有这个时,如何从 Android 对 Firebase rest api 进行身份验证 数据库规则:

"TOY_STORE": {
  ".read": "auth != null",
  ".write": "auth != null"
},

如果我设置 ".read": "true" 我可以使用此代码访问点头

 com.loopj.android.http.AsyncHttpClient client = new AsyncHttpClient();
    client.get("https://xxx-project.firebaseio.com/TOY_STORE/.json?print=pretty&shallow=true?auth=HnhLyXRxUsadhj237eYiQ53",  new JsonHttpResponseHandler() {

// respons..
}

但是当有 ".read": "auth != null" 时,它会拒绝授予权限。

我使用 Google 凭据登录到 Firebase,auth=HnhLyXRxUsadhj237eYiQ53 是我的 Firebase ID。我可以定期进行 ValueEventListenerupdateChildren 调用来读取和写入数据库。

我也尝试过 Web API 密钥进行身份验证,但无法正常工作。

我想要 运行 这段代码因为

如果你想通过规则“.read”从 firebase 读取:"auth != null" 并且你不想使用 firebase api 我推荐 Retrofit2 库。您必须通过 Bearer 服务帐户令牌进行身份验证。

警告!令牌仅在一小时内有效。然后你需要刷新新的token。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

....

//mykey.json you get from FBconsole/Project Settings/service accounts/generte new private key

    myFile = new File(mykey.json);


    GoogleCredential googleCred = null;
    try {
        googleCred = GoogleCredential.fromStream(new FileInputStream(myFile));
    } catch (IOException e) {
        e.printStackTrace();
    }
    GoogleCredential scoped = googleCred.createScoped(
            Arrays.asList(
                    "https://www.googleapis.com/auth/firebase.database",
                    "https://www.googleapis.com/auth/userinfo.email"
            )
    );
    try {
        scoped.refreshToken();
    } catch (IOException e) {
        e.printStackTrace();
    }
    token = scoped.getAccessToken();
    Log.d("token ", token);




}//end of oncreate

点击按钮从 FB 读取

public void onClick(View view) {


    authtoken = "Bearer " + token;

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request original = chain.request();

            // Request customization: add request headers
            Request.Builder requestBuilder = original.newBuilder()
                    .header("Authorization", authtoken); // <-- this is the important line
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });

    httpClient.addInterceptor(logging);
    OkHttpClient client = httpClient.build();



    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://yourproject.firebaseio.com")//url of firebase database app
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())//use for convert JSON file into object
            .build();

    // prepare call in Retrofit 2.0
    FirebaseAPI firebaseAPI = retrofit.create(FirebaseAPI.class);

    Call<Event> call2=firebaseAPI.getPrivateData();

    call2.enqueue(new Callback<Event>() {
        @Override
        public void onResponse(Call<Event> call, Response<Event> response) {

            Log.d("Response ", "onResponse");
            //t1.setText("success name "+response.body().getName());


        }

        @Override
        public void onFailure(Call<Event> call, Throwable t) {
            Log.d("Response ", "onFailure");
            //t1.setText("Notification failure");
        }
    });
}

FirebaseAPI.java

public interface FirebaseAPI {

@GET("/uploadprivate/event.json")
Call<Event> getPrivateData();

}

POJOevent.java

public class Event {
String name;
String address;

public Event(String name, String address) {
    this.address = address;
    this.name = name;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}


}

FB控制台中的数据

可以找到使用 REST API 进行身份验证的文档 here。您需要在查询字符串中传递一个带有用户身份验证令牌值的 auth 参数。

将您的数据库密钥放入您的应用程序中是一个非常糟糕的主意,任何人都可以轻松地对其进行逆向工程。但是如果你想从你控制的服务器上使用 REST API,你可以在项目设置 -> 服务帐户 -> 数据库机密中找到你的数据库密钥。