8
votes

I am attempting to initialize the Firebase Admin SDK using a Heroku instance running a Java Spring application. The Firebase instructions reference the .json file directly.

Initialize the Firebase Admin SDK

I do not want to include my admin SDK json file directly in my git repo because I don't want my firebase credentials exposed. To access the .json values in Heroku I have created an environment variable with the contents of the Firebase Admin SDK .json file inside of it. I have done the same thing in my local development environment and the app works by accessing the environment var using this method:

String serviceAccountJson = System.getenv("SERVICE_ACCOUNT_JSON");
InputStream serviceAccount = new ByteArrayInputStream(serviceAccountJson.getBytes(StandardCharsets.UTF_8));
FirebaseOptions options = new FirebaseOptions.Builder()
    .setCredential(FirebaseCredentials.fromCertificate(serviceAccount))'
    .setDatabaseUrl("https://myfirebase-app.firebaseio.com/")
    .build();
FirebaseApp.initializeApp(options);

When I attempt to run the app in Heroku it crashes when firebase tries to initialize.

Are there any work arounds or other methods to access a .json file that is not in a .git repo, but available on a Heroku server?

2
stackoverflow.com/a/69085611/11885333 works for me as of september 2021 - keemahs

2 Answers

2
votes

I was running into the same issue. You just need to escape any special characters in the json with something like this.

0
votes

I can't remember why, but you need to fix the whitespace in the JSON env var like this:

private static String massageWhitespace(String s) {
    String newString = "";
    for (Character c : s.toCharArray()) {
        if ("00a0".equals(Integer.toHexString(c | 0x10000).substring(1))) {
            newString += " ";
        } else {
            newString += c;
        }
    }
    return newString;
}

Here's a working example app