Firebase服务帐户凭据Json读取权限被拒绝

时间:2016-06-17 07:09:19

标签: android json google-app-engine google-cloud-endpoints firebase-realtime-database

我从Firebase控制台下载了我的服务帐户凭据json文件,将其放在GAE端点项目的主目录中,当我在本地运行支持时,它提供了安全性异常。

java.security.AccessControlException: access denied ("java.io.FilePermission" "\src\main\secret.json" "read")

我尝试将 .json 文件放在 src 目录下,但没有帮助。

3 个答案:

答案 0 :(得分:0)

您应该将json文件放在src/main/resources

答案 1 :(得分:0)

我找到了几种方法来解决这个问题。首先是通过互联网流从文件中获取它。另一个是本地的。

INTERNET WAY

我的第一种方法是将文件存储在公共Dropbox文件夹中。我获得了可共享的链接(确保它以.json结尾)并将其粘贴到字符串示例中"https://dl.dropboxusercontent.com/..EXAMPLE-CREDENTIALS"

/** A simple endpoint method that takes a name and says Hi back */
    @ApiMethod(name = "sayHi")
    public MyBean sayHi(@Named("name") String name) {

        MyBean mModelClassObject = null;

        String text = "";

        try {
            String line = "";
            StringBuilder builder = new StringBuilder();
            URL url = new URL("https://dl.dropboxusercontent.com/..EXAMPLE-CREDENTIALS");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));


            while ((line = reader.readLine()) != null) {
                // ...
                builder.append(line);
            }
            reader.close();

            text = builder.toString();
        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }

        InputStream stream = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));

        FirebaseOptions options = null;
        options = new FirebaseOptions.Builder()
                .setServiceAccount(stream)
                .setDatabaseUrl("https://[PROJECT-ID].firebaseio.com/")
                .build();
        FirebaseApp.initializeApp(options);

        DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
        final TaskCompletionSource<MyBean> tcs = new TaskCompletionSource<>();


        Task<MyBean> tcsTask = tcs.getTask();

        ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                MyBean result = dataSnapshot.getValue(MyBean.class);
                if(result != null){
                    tcs.setResult(result);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError){
                //handle error
            }
        });

        try {
            mModelClassObject = Tasks.await(tcsTask);
        }catch(ExecutionException e){
            //handle exception
        }catch (InterruptedException e){
            //handle exception
        }

        return mModelClassObject;
    }

本地方式

另一种方法是使用上面的版本并跳过像dropbox这样的东西

/** A simple endpoint method that takes a name and says Hi back */
        @ApiMethod(name = "sayHi")
    public MyBean sayHi(@Named("name") String name) {

        MyBean mModelClassObject = null;

        String text = "JUST PASTE YOUR JSON CONTENTS HERE";

        InputStream stream = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));

        FirebaseOptions options = null;
        options = new FirebaseOptions.Builder()
                .setServiceAccount(stream)
                .setDatabaseUrl("https://[PROJECT-ID].firebaseio.com/")
                .build();
        FirebaseApp.initializeApp(options);

        DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
        final TaskCompletionSource<MyBean> tcs = new TaskCompletionSource<>();


        Task<MyBean> tcsTask = tcs.getTask();

        ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                MyBean result = dataSnapshot.getValue(MyBean.class);
                if(result != null){
                    tcs.setResult(result);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError){
                //handle error
            }
        });

        try {
            mModelClassObject = Tasks.await(tcsTask);
        }catch(ExecutionException e){
            //handle exception
        }catch (InterruptedException e){
            //handle exception
        }

        return mModelClassObject;
    }

我不知道这是否遵循最佳做法,但我的项目现在正在运作。 我还提供了firebase的代码来获取信息。看看我最近询问的有关阅读和写入firebase的question的答案。

修改

清理了不会抛出错误的版本

public class MyEndpoint {

    private FirebaseOptions options;
    private DatabaseReference ref;
    private String serviceAccountJSON = "i took mine out for security reasons";

    // create firebase instance if need be
    private void connectToFirebase(){
        if (options == null) {
            options = null;
            options = new FirebaseOptions.Builder()
                    .setServiceAccount(new ByteArrayInputStream(serviceAccountJSON.getBytes(StandardCharsets.UTF_8)))
                    .setDatabaseUrl("https://[PROJECT-ID].firebaseio.com/")
                    .build();
            FirebaseApp.initializeApp(options);
        }
        if(ref == null) {
            ref = FirebaseDatabase.getInstance().getReference();
        }
    }

    /** A simple endpoint method that takes a name and says Hi back */
    @ApiMethod(name = "sayHi")
    public MyBean sayHi(@Named("name") String name) {

        // always do this first
        connectToFirebase();

        MyBean mModelClassObject = null;

        final TaskCompletionSource<MyBean> tcs = new TaskCompletionSource<>();
        Task<MyBean> tcsTask = tcs.getTask();

        // get the info
        ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                MyBean result = dataSnapshot.getValue(MyBean.class);
                if(result != null){
                    tcs.setResult(result);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError){
                //handle error
            }
        });

        // wait for it
        try {
            mModelClassObject = Tasks.await(tcsTask);
        }catch(ExecutionException e){
            //handle exception
        }catch (InterruptedException e){
            //handle exception
        }

        mModelClassObject.setData(mModelClassObject.getData() + name);

        return mModelClassObject;
    }
}

答案 2 :(得分:0)

最后,我找到了解决方案,它是在link的Google App Engine的API和参考部分下编写的,我们需要在{{1}下的appengine-web.xml文件中添加这些文件标签,使用<resource-files>属性。这样做之后它对我有用。我将包含项目凭据的.json文件放在WEB-INF目录中,然后在<include path=""/>标记中输入其相对路径。