MediaLink issue when creating a file to Bucket - firebase

I am using GoLang along as Google App Engine for hosting my web services.
I have been succesful in creating a file to my Firebase storage bucket, but then I would like to get a clean url for it that can be retrieved by clients (iOS / Android) that are authentified with firebase Auth.
What would be the easiest way to get such a link ?
What I have tried :
Getting ObjAttrs object, the bucket object attributes after the creation of the file :
This way in Go
attrs, err := obj.Attrs(ctx)
and I do get the attributes, among them a value called MediaLink
A sample of this link would be "https://www.googleapis.com/download/storage/v1/b/MY_BUCKET/o/MY_FOLDER%2FMY_FILE_NAME?generation=1539262480095558&alt=media"
Problems :
If I try to open this link into a browser, I get the following error : "Anonymous caller does not have storage.objects.get access to...."
Fair enough, since I'm not authentified with Firebase Auth at this point
But I also tried from a iOS client which is properly authentified with Firebase Auth, and still the retrieval of the link failed.
On the web console, attached to my file in my bucket, I see a link such as this "https://firebasestorage.googleapis.com/v0/b/MY_BUCKET/o/MY_FOLDER%2FMY_FILENAME?alt=media&token=47630584-f05c-43a2-a04d-8fc21d207181"
This works on both browser and iOS clients.
Now is how can I get by code, in GOLang such URL ?
I have seen no documentation about this.

Related

Firebase storage returning 412 error even after enabling storage API

We have already used firebase storage for storing the images and files in our application. Recently our files seem to bee not loading in the application and once cross-checking I found the following error.
{
"error": {
"code": 412,
"message": "A required service account is missing necessary permissions. Please resolve by visiting the Storage page of the Firebase Console and re-linking your Firebase bucket or see this FAQ for more info: https://firebase.google.com/support/faq#storage-accounts"
}
}
After further investigation, I found a solution in the below-related FAQ.
https://firebase.google.com/support/faq/index#storage-accounts
As per the documentation, I have created a new service account with the I am admin role as Cloud Storage for Firebase Service Agent. It created a service account called service account name service-PROJECT_NUMBER#PROJECT_id.iam.gserviceaccount.com. Also, I have enabled the IAM admin policies for managing services. But still but storage URL is not loading.
Do I need to add any more changes to storage permissions? How can I use the existing storage bucket data with the new updates?
I just fixed this for my self.
Create a bucket in Cloud Storage
Get your projectname and bucket name
Go here: https://firebase.google.com/docs/reference/rest/storage/rest/v1beta/projects.buckets/addFirebase
Press Try IT
Fill in your projectname en bucket name. Press Execute é voila!
See my screenshot here
As mentioned in this github.
On the IAM page with the project owner role you will have an option to Grant Access.
add this service account.
service-project number#gcp-sa-firebasestorage.iam.gserviceaccount.com as a principle, Cloud Storage for Firebase Service Agent as role.
If you are having trouble adding the service account (service-#gcp-sa-firebasestorage.iam.gserviceaccount.com) to the project, it's possible that Cloud Storage for Firebase has not created it yet.
Try using the AddFirebase API to relink a bucket to your project and try again: You can refer to this
I fixed the issue with the following steps.
After setting the IAM policies in storage admin I tried with AddFirebaseAPI function using postman by passing the project id and storage bucket name. But it returns a not found error for me. I tried it with both project number as well as id. Both given the same error.
About the error using Postman and the URL this should be working it solved by using
https://firebasestorage.googleapis.com/v1beta/projects/<projectid>/buckets/<bucketname>:addFirebase
Here is an example of the HTTP call that the playground gives you
POST
https://firebasestorage.googleapis.com/v1beta/projects/<projectid>/buckets/<bucketname>:addFirebase?key=[YOUR_API_KEY] HTTP/1.1
Authorization: Bearer [YOUR_ACCESS_TOKEN]
Accept: application/json
Content-Type: application/json
It will returns your bucket instance. Also it may takes a few mins to reflect the changes.
If you open firebase-storage in console.firebase.google.com, it gives you an alert saying attach permission. If you click on it, problem should be fixed automatically.
If it doesn't solve, then follow this Github
If you don't find project number #gcp-sa-firebasestorage.iam.gserviceaccount.com in console permission, then make sure you click on attach permission dialog in firebase storage.
This is how my problem was solved.

How to get firebase App Check working with cloud firestore in a web app

I try to get App Check working in my vue.js pwa. Using the latest firebase sdk and by following steps here https://firebase.google.com/docs/app-check/web/recaptcha-provider
My api key (https://console.cloud.google.com/apis/credentials/key..) is not limited to any API restrictions. I did add some Application Restrictions on https tho including my project domains.
Everything works fine till i activate appCheck with recaptcha v3 and i get following console errors:
FirebaseError: [code=unknown]: Fetching auth token failed: AppCheck: Fetch server returned an HTTP error status. HTTP status: 403. (appCheck/fetch-status-error)
Further more the app can't get any firebase data or auth. I tried in several browsers and without any vpn stuff.
In my already installed pwa the App Check error occurs but connection to firebase still works..
Without App Check activated it both works without an issue. Also with an App Check debug token the whole thing just works. I don't understand why it breaks firebase connection even if i haven't enabled enforcement.
I appreciate any tips on how to solve this.
I found the problem i accidently left self.FIREBASE_APPCHECK_DEBUG_TOKEN = true; in my production code.
Remove this line or only use when in development envirement solved the whole problem
if (location.hostname === "localhost") {
self.FIREBASE_APPCHECK_DEBUG_TOKEN = true;
}
I didn't expect this line to impact browsers where i haven't registered a debug token to fail with the regular appCheck but of course it doesn't make sense to use it in production anyways.
Based on your question, you want to enable Firebase App Check for Firestore with Web Application. Currently, Firestore App Check does not support it.
As per this Documentation:
Cloud Firestore support is currently available only for Android and iOS clients. If your project has a web app, don't enable Cloud Firestore enforcement until web client support is available.
I'll leave an answer for people who have problems with the setup. For the more detailed answer, you can check this question.
In short, you need to do a few steps.
Set up a firebase.
Go to how to set up app check.
Register reCAPTCHA here and add the secret_key to the Firebase console, and the site_key to your web code.
Initialize the Firebase in your code based on how to set up app check docs.
Get your debug_key and add it to your firebase console and code.
Finally, the code should look something like this:
Don't forget to save your key to a .env file or firebase.js or somewhere where you won't upload it to git.
if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
window.FIREBASE_APPCHECK_DEBUG_TOKEN = 'your_debug_token';
}
const appCheck = initializeAppCheck(app, {
provider: new ReCaptchaV3Provider('your_site_key_from_register'),
// Optional argument. If true, the SDK automatically refreshes App Check
// tokens as needed.
isTokenAutoRefreshEnabled: true
});

firebase firestore gives error for a project that's been added to firebase projects

I've added my project to firestore and I'm doing firestore google auth just fine.
My problem is firebase firestore.
It just doesn't work and I have no idea why.
I'm trying to do a simple add before doing the actual process for my app and it doesn't work.
here I implemented a simple function to add a user and then called it, doing it all in build function.
I get this in my console:
p.s.
"adding user" is printed on console.
p.s.
I do have the firebase_options.dart file.
These thing are you sure that the correct:
1.Using correct google_services.json file
2.Edit Fire store rules if you are not using authorization
You have to manually whitelist your existing Google OAuth 2.0 client IDs in the Firebase console before using it with the new Auth APIs.
In order to do so, follow these steps:
Go to the Credentials section in the Google API Console.
Select from the top right corner the project where you had previously configured Google Sign-In.
Go to the OAuth 2.0 client IDs section
If you are using Google Sign-In on Android or iOS applications:
Take note of the Client ID string corresponding to all the entries registered for your applications.
Input these Client IDs into your Firebase project’s configuration:
Go to the Firebase console at https://console.firebase.google.com
Open the Auth section
Under Sign-In methods, open the Google configuration, and add there all you client IDs, to the whitelist of client IDs from external projects.
If you are using Google Sign-In on a web application:
Click to open your web client ID and take note of both the client ID and secret.
Input this Client ID into your Firebase project’s configuration:
Go to the Firebase console at https://console.firebase.google.com
Open the Auth section
Under Sign-In methods, open the Google configuration, and add the values under the Web SDK configuration section.

Can I make firebase file URLs publicly available without requiring token?

I am using firebase to allow users to upload their files to the Storage buckets. I was using the getDownLoadURL() to fetch the publicly available URL...however, this comes with an embedded token to allow access to the file.
In my same app, I'm using the Google Document viewer which takes a URL to preview the doc. Unfortunately, the Google Doc Viewer does not work with the firebase URLs's with the embedded token.
In Google Console, on an individual file, I click to make it public. In that case, the URL is now reachable via the https://storage.googleapis.com// format...and I don't need to use the token which works great.
So, what I want to do is mark/make a file public when I'm uploading it to firebase. I have reviewed the firebase docs and there doesn't seem to be a makePublic() method like there is on the Google API's.
Is there a way I can mark a file as public during upload, so that it can be accessed without any token?
The other solution was that I could update the bucket to be accessible, but this makes it totally open to be browsed at https://storage.googleapis.com/, which I don't want to do.
The client-side Firebase APIs don't know anything about the underlying Google Cloud Platform configurations for public content in storage buckets. So that won't be an option.
You will have to involve some backend code to change the object's configuration after it's uploaded. You could set up your own API endpoint via Cloud Functions (or whatever backend you want) to run one of the Google Cloud Storage server SDKs to set the file as public. (You will probably also want some way to authorize that the user calling your API should be able to make this change.)

How to upload the files to firebase storage with uid using Post Url?

I found one solution to upload the file to firebase storage without any authentication using this link How to upload objects to Firebase Storage using Postman for testing?
The above-mentioned case works only when my firebase storage looks like this, (Without any security restriction)
allow read, write;
But, Now I want to achieve this with some security restrictions.
Is there any way to upload the files to firebase storage by POST URL (Postman) with some security restriction.
I tried to achieve this by
https://firebasestorage.googleapis.com/v0/b/projectName.bucketName.com/o?uploadType=media&name=picture2&auth=uid
But it shows 403 - forbidden error.
There is no public REST API for uploading file to Cloud Storage for Firebase. The end point you're trying to reach is meant for use by the Firebase SDK only, and is neither documented, nor supported for use beyond that.
That said, you may be able to mint a token using the Firebase Authentication REST API, and pass that along to the request you have. But as said, it won't be supported and may change without warning.
The most common approach for REST uploads is through the Google Cloud Storage API, around which the Firebase APIs are a friendly wrapper. But these APIs are meant for access from trusted code, so wouldn't be using the Firebase Authentication UID of your users. The best I can think of is to write a Cloud Function that handles the user authentication and authorization, and then use the Google Cloud Storage Node.js or REST API to upload the file.
I use this endpoint on my project
https://firebasestorage.googleapis.com/v0/b/YOUR_BUCKET/o?uploadType=media&name=YOUR_FILE_PATH_AND_NAME
and add headers on your post
headers.Add("Authorization", "Bearer " + FirebaseAuthIDToken);
headers.Add("Content-Type", "application/octet-stream");

Resources