Use without preparing an authentication file when using Firebase Admin SDK in Java

Introduction

If you want to use Firebase Admin SDK in Java, you need to initialize Firebase as below.

Initialization


FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountKey.json");

FirebaseOptions options = new FirebaseOptions.Builder()
    .setCredentials(GoogleCredentials.fromStream(serviceAccount))
    .setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/")
    .build();

FirebaseApp.initializeApp(options);

The problem here is that you need to load the json file downloaded from the Firebase Console. Normally, confidential information is passed as an environment variable, but for some reason a json file that describes confidential information is required.

For example, when deploying to the server triggered by push to GitHub with Ci / CD etc. You also need to push this json file. Even if your repository is private, it's dangerous to manage.

So, as the title says, I will show you how to set from environment variables without preparing a file.

Operating environment

Preparation

Download the service account private key information from the Firebase Console.

スクリーンショット_2019-03-26_23_20_11.png

procedure

Setting environment variables

Add the following code to launch.json. Please refer to the json file of private key information for the setting value.

launch.json


"env": {
        "TYPE": "<type>",
        "PROJECT_ID": "<project_id>",
        "PRIVATE_KEY": "<private_key>",
        "PRIVATE_KEY_ID": "<private_key_id>",
        "CLIENT_EMAIL": "<client_email>",
        "CLIENT_ID": "<client_id>",
        "CLIENT_X509_CERT_URL": "<client_x509_cert_url>"
}

Implementation

You can create a json file programmatically.

@SpringBootApplication
public class DemoApplication {

	private static final String FIREBASE_CREDENTIALS_PATH = "/path/to/credentials.json";
	private static ObjectMapper mapper = new ObjectMapper();

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
		try {
			FileWriter fw = new FileWriter(FIREBASE_CREDENTIALS_PATH);
			try (PrintWriter pw = new PrintWriter(new BufferedWriter(fw))) {
                //Get from environment variables and set
				Map<String, String> credentials = new HashMap<>();
				credentials.put("type", System.getenv("TYPE"));
				credentials.put("project_id", System.getenv("PROJECT_ID"));
				credentials.put("private_key_id", System.getenv("PRIVATE_KEY_ID"));
				credentials.put("private_key", System.getenv("PRIVATE_KEY"));
				credentials.put("client_email", System.getenv("CLIENT_EMAIL"));
				credentials.put("client_id", System.getenv("CLIENT_ID"));
				credentials.put("auth_uri", "https://accounts.google.com/o/oauth2/auth");
				credentials.put("token_uri", "https://oauth2.googleapis.com/token");
				credentials.put("auth_provider_x509_cert_url", "https://www.googleapis.com/oauth2/v1/certs");
				credentials.put("client_x509_cert_url", System.getenv("CLIENT_X509_CERT_URL"));
                //Convert Map to Json format string
				String str = mapper.writeValueAsString(credentials);
                //Write to file
				pw.println(str);
			}
			FileInputStream serviceAccount = new FileInputStream(FIREBASE_CREDENTIALS_PATH);

			FirebaseOptions options = new FirebaseOptions.Builder()
					.setCredentials(GoogleCredentials.fromStream(serviceAccount)).build();
            //Initialization
			FirebaseApp.initializeApp(options);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

	}

Recommended Posts

Use without preparing an authentication file when using Firebase Admin SDK in Java
Map without using an array in java
When calling println etc. from an external Java class file in Processing
Summary when trying to use Solr in Java and getting an error (Solr 6.x)
When using a list in Java, java.awt.List comes out and an error occurs
[Java] Creating an Excel file using Apache POI
I tried using an extended for statement in Java
Differences in code when using the length system in Java
I want to use Java Applet easily on the command line without using an IDE
Use OpenCV in Java
Use PreparedStatement in Java
Use Java Web Start in an OpenJDK environment on Windows
Things you often use when doing web development in Java
Get attributes and values from an XML file in Java
Access S3 buckets using SSE-KMS encryption in an EC2 IAM Role environment (AWS SDK for Java)