firebase / firebase-admin-dotnet

Firebase Admin .NET SDK
https://firebase.google.com/docs/admin/setup
Apache License 2.0
369 stars 131 forks source link

Initialize Firebase Admin with enviroment variables instead of service-account.json file #339

Closed pasindu-pr closed 1 year ago

pasindu-pr commented 1 year ago

I have initialized Firebase Admin in one of my .NET projects like this.

services.AddSingleton(FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.FromFile("./firebase-settings.json"), } ));

But when I deploy this to production, for example in Azure App service, I have to do a workaround to push this JSON file to the App Service, since we shouldn't add the JSON file to the source control.

So Instead of using this approach, is there a way to initialize this package by passing the projectid, private key, etc to the appSettings.json file and providing those credentials to the package using the code, instead of adding the JSON file path?

I saw that this approach is available for Nodejs as follows, But is there an equivalent for .NET?

admin.initializeApp({ credential: admin.credential.cert({ projectId: process.env.FIREBASE_PROJECT_ID, clientEmail: process.env.FIREBASE_CLIENT_EMAIL, privateKey: process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n'), }), })

google-oss-bot commented 1 year ago

I found a few problems with this issue:

lahirumaramba commented 1 year ago

Hi @PasinduPrabhashitha ,

You can store the contents of the key in a secret or in an environment variable in your production environment and load the credentials from json.

FirebaseApp = FirebaseApp.Create(new AppOptions()
                {
                    Credential =
                        GoogleCredential.FromJson(...),
                });

If you can upload the key file to your production service set the environment variable GOOGLE_APPLICATION_CREDENTIALS and use GoogleCredential.GetApplicationDefault(). See Initialize the SDK in non-Google environments for more on this.

GoogleCredentials API is part of googleapis/google-api-dotnet-client. You can see all the supported ways to initialize credentials in that codebase.

Additionally, service account keys can become a security risk if they are not managed properly. Look into workload identity federation to authenticate your apps without a service account key.