Flutter firebase storage CORS issue - firebase

I'm using a free plan of firebase storage. All working good but the image not loading on my flutter web.
I'm getting this error.
Access to XMLHttpRequest at 'https://firebasestorage.googleapis.com/v0/b/sap-app-8318e.appspot.com/o/cover%2Fimage_cropper_028D7F16-0161-4E90-B40D-EE47D310F322-5339-000003697F67306C.jpg?alt=media&token=313475a9-9728-4e61-97da-f5d5534bb008' from origin 'https://sap.nextcardpro.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
firebasestorage.googleapis.com/v0/b/sap-app-8318e.appspot.com/o/cover%2Fimage_cropper_028D7F16-0161-4E90-B40D-EE47D310F322-5339-000003697F67306C.jpg?alt=media&token=313475a9-9728-4e61-97da-f5d5534bb008:1
I searched on google everyone told need to allow CORS Access from firebase, but how can I have to add it. but how can I add it to my free firebase plan?
[
{
"origin": ["*"],
"responseHeader": ["Content-Type"],
"method": ["GET", "HEAD", "DELETE"],
"maxAgeSeconds": 3600
}
]

Finally, solve by this post after 2 days of google search.
https://bitmovin.com/docs/encoding/faqs/how-do-i-set-up-cors-for-my-google-cloud-storage-bucket

Answer from above link:
If you already familiar with Google Cloud Services and Tools, like gcloud and/or gsutil, you can also checkout Google's documentation about CORS.
Login to your google cloud console: https://console.cloud.google.com/home. Click on "Activate Google Cloud Shell" in the upper right corner (see picture below):
At the bottom of your window, a shell terminal will be shown, where gcloud and gsutil are already available. Execute the command shown below. It creates a json-file which is needed to setup the cors-configuration for your bucket. This configuration will allow every domain to access your bucket using XHR-Requests in the browser: echo '[{"origin": ["*"],"responseHeader": ["Content-Type"],"method": ["GET", "HEAD"],"maxAgeSeconds": 3600}]' > cors-config.json
If you want to restrict the access one or more specific domains, add their URL to the array, e.g.: echo '[{"origin": ["https://yourdomain.com", "http://localhost:*"],"responseHeader": ["Content-Type"],"method": ["GET", "HEAD"],"maxAgeSeconds": 3600}]' > cors-config.json
(localhost is also added to access resources while developing, based on your needs).
Replace YOUR_BUCKET_NAME with your actual bucket name in the following command to update the cors-settings from your bucket gsutil cors set cors-config.json gs://YOUR_BUCKET_NAME
To check if everything worked as expected, you can get the cors-settings of a bucket with the following command: gsutil cors get gs://YOUR_BUCKET_NAME
You can find the bucket ID in the Storage panel of your project's Firebase Console:
Storage Panel of the Firebase Console
It's the value starting with gs://.

I had a similar problem and as always, it took me few hours to fix but the solution is as always simple and easy.
When you run this command flutter run -d chrome --web-renderer canvaskit --no-sound-null-safety app will run and everything works fine and pixel-perfect but sadly network images failed to load. When you inspect the app look into console you will see this beautiful error
(Blocked by CORS policy) : No ‘Access-Control: Allow-Origin’ header is present on the requested resource.
What is CORS?
CORS stands for (Cross-Origin-Resource-Sharing). CORS is a browser security feature that restricts Cross-origin HTTP requests that are initiated from scripts running in the browser.
Now how to fix CORS issue? And displaying images from any other domain or from Firebase Storage. The answer is very simple follow me with the steps below
Open the GCP console you will see the screen below
Now select your project and click on the dashboard Button.
Start a cloud terminal by clicking the >_ icon button in the top navbar as you can see in the below image
Click on the open editor button and (wait for few seconds)
Now click on 3 (...) dot and create new file and named it cors.json like you can see in the below image
Copy and paste the this code
[ { "origin": ["*"], "method": ["GET"], "maxAgeSeconds": 3600 } ]
In the code you notice i set the origin * which means that every website can display your images. But you can also insert the domain of your website there to restrict the access.
Now run the command : gsutil cors set cors.json gs://your-bucket When you run gsutil cors set cors.json gs://your-bucket you will get beautiful error (‘gsutil ServiceException: 401 Anonymous caller does not have storage.objects.list access to bucket’) it’s mean you need to login first.
Run this command gcloud auth login and login into gcloud
Now again run this command gsutil cors set cors.json gs://your-bucket
if you want to read more about CORS: https://cloud.google.com/storage/docs/configuring-cors

If somebody has a problem with installing gsutil. It will not work with python 3.10 which is the most recent one. You have to install a previous one, which version number starts with 3.7
like this one:
download python 3.7.9

Official Firebase Storage answer can be found here. May be useful if the answer ever changes. As of April 2022, it's basically the same as Feroz's answer.

Related

Firebase 3rd-party AuthProvider (Google/Facebook/etc) login with chrome extension manifest v3

Manifest version 3 for Chrome extensions have been killing me lately. Been able to navigate around it so far, but this one has really stumped me. I'm trying to use Firebase authentication for a Chrome extension, specifically with 3rd party auth providers such as Google and Facebook. I've setup the Firebase configuration for Login with Google and created a login section in the options page of the Chrome extension and setup the Firebase SDK.
Now, there are two login options when using an auth provider, signInWithRedirect and signInWithPopup. I've tried both of these and both have failed for different reasons. signInWithRedirect seems like a complete dead end as it redirects to the auth provider, and when it attempts to redirect back to the chrome-extension://.../options.html page, it just redirects to "about:blank#blocked" instead.
When attempting to use signInWithPopup, I instead get
Refused to load the script 'https://apis.google.com/js/api.js?onload=__iframefcb776751' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
In v2, you could simply add https://apis.google.com to the content_security_policy in the manifest. But in v3, the docs say
"In addition, MV3 disallows certain CSP modifications for extension_pages that were permitted in MV2. The script-src, object-src, and worker-src directives may only have the following values:"
self
none
Any localhost source, (http://localhost, http://127.0.0.1, or any port on those domains)
So is there seriously no way for a Google Chrome extension to authenticate with a Google auth provider through Google's Firebase? The only workaround I can think of is to create some hosted site that does the authentication, have the Chrome extension inject a content script, and have the hosted site pass the auth details back to the Chrome extension through an event or something. Seems like a huge hack though and possibly subject to security flaws. Anyone else have ideas??
Although it was mentioned in the comments that this works with the Google auth provider using chrome.identity sadly there was no code example so I had to figure out myself how to do it.
Here is how I did it following this tutorial:
(It also mentions a solution for non-Google auth providers that I didn't try)
Identity Permission
First you need permission to use the chrome identity API. You get it by adding this to your manifest.json:
{
...
"permissions": [
"identity"
],
...
}
Consistent Application ID
You need your application ID consistent during development to use the OAuth process. To accomplish that, you need to copy the key in an installed version of your manifest.json.
To get a suitable key value, first install your extension from a .crx file (you may need to upload your extension or package it manually). Then, in your user data directory (on macOS it is ~/Library/Application\ Support/Google/Chrome), look in the file Default/Extensions/EXTENSION_ID/EXTENSION_VERSION/manifest.json. You will see the key value filled in there.
{
...
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgFbIrnF3oWbqomZh8CHzkTE9MxD/4tVmCTJ3JYSzYhtVnX7tVAbXZRRPuYLavIFaS15tojlRNRhfOdvyTXew+RaSJjOIzdo30byBU3C4mJAtRtSjb+U9fAsJxStVpXvdQrYNNFCCx/85T6oJX3qDsYexFCs/9doGqzhCc5RvN+W4jbQlfz7n+TiT8TtPBKrQWGLYjbEdNpPnvnorJBMys/yob82cglpqbWI36sTSGwQxjgQbp3b4mnQ2R0gzOcY41cMOw8JqSl6aXdYfHBTLxCy+gz9RCQYNUhDewxE1DeoEgAh21956oKJ8Sn7FacyMyNcnWvNhlMzPtr/0RUK7nQIDAQAB",
...
}
Copy this line to your source manifest.json.
Register your Extension with Google Cloud APIs
You need to register your app in the Google APIs Console to get the client ID:
Search for the API you what to use and make sure it is activated in your project. In my case Cloud Firestore API.
Go to the API Access navigation menu item and click on the Create an OAuth 2.0 client ID... blue button.
Select Chrome Application and enter your application ID (same ID displayed in the extensions management page).
Put this client ID in your manifest.json. You only need the userinfo.email scope.
{
...
"oauth2": {
"client_id": "171239695530-3mbapmkhai2m0qjb2jgjp097c7jmmhc3.apps.googleusercontent.com",
"scopes": [
"https://www.googleapis.com/auth/userinfo.email"
]
}
...
}
Get and Use the Google Auth Token
chrome.identity.getAuthToken({ 'interactive': true }, function(token) {
// console.log("token: " + token);
let credential = firebase.auth.GoogleAuthProvider.credential(null, token);
firebase.auth().signInWithCredential(credential)
.then((result) => {
// console.log("Login successful!");
DoWhatYouWantWithTheUserObject(result.user);
})
.catch((error) => {
console.error(error);
});
});
Have fun with your Firebase Service...

google cloud vision api quickstart error opening file

I am following the following Google Cloud Vision quickstart:
https://cloud.google.com/vision/docs/quickstart
This is using the API Explorer, and I get
Error Opening File
I have created a bucket named vision2018, and checked Share Publicly for the file.
My portion of the request related to the file is:
"image":
{
"source":
{
"imageUri":"gs://vision2018/demo-image.jpg"
}
}
The response I get is:
{
"responses": [
{
"error": {
"code": 5,
"message": "Error opening file: gs://vision2018/demo-image.jpg\"."
}
}
]
}
}
What do I need to specify in order to access files in my GCP storage?
Alternatively, I read other Stack Overflows that talk about GOOGLE_APPLICATION_CREDENTIALS, Simple API Key, and "Create Service account key and download the key in JSON format", ... but these seem to be giving commands in the shell, which this quickstart doesn't even open.
Is there initial setup assumed prior to the quickstart?
I am not ready to call the api from code
You might want to doublecheck your request. I went to the quickstart, replaced the placeholder imageUri with gs://vision2018/demo-image.jpg and it worked just fine. The error message you posted is what would be displayed if you had given gs://vision2018/demo-image.jpg\" instead.
Regarding the second part of your question: these are authentication methods. In this particular case, under Authentication you will find a drop down which lets you chose between API key and Google OAuth 2.0. If you chose the former, you don't need to do anything as a demo key will be used just for the purposes of the quickstart. If you chose OAuth 2.0, a popup will appear prompting you to authenticate with a google account. All in all, what you need to do is follow step-by-step the instructions given by the quickstart.
I was receiving a similar JSON response from the Google Vision API:
"error": {
"code": 7,
"message": "Error opening file: gs://bucket/file.jpg."
}
The fix was to set the GCS file's permission to public-read:
gsutil acl set public-read gs://bucket/file.jpg
Finally I investigated what happened. The problem is that your API token is only grant for process the image (allow right to use OCR engine), but that API is not also for accessing object in GS.
Therefore "message": "Error opening file:
The problem is similar with this post:Authorize Google Cloud Vision API to Google Storage image Maybe the error message is a bit dumb than many years ago.
The solution also mentioned in the answer section, but if you want some thing more clear (expose security side-effect) here it is: Set GCS read-only public
Reason I want to keep using API because it's better for use it in mobile application, we cannot give the OAuth2.0 to any phone. However, still find a way to secure the read-public bucket.

Google push notifications - DOMException: Registration failed - permission denied

I'm following the (getting started with push locations guide) but am running into an error on step 6:
undefined:1 Uncaught (in promise) DOMException: Registration failed - permission denied
My manifest.json file is loading correctly based on the Network tab.
I have entered my correct project number into manifest.json. I have tried adding other settings not mentioned in the guide:
{
"name": "Push Notifications codelab",
"gcm_sender_id": "123456789",
"gcm_user_visible_only": true,
"permissions": [
"gcm"
]
}
I am running my server on localhost as per the guide.
If you're using Brave(the browser) and having the same issue, you have to enable Use Google Services for Push Messaging in the settings.
In order to enable it:
Brave settings > Privacy and Security > Use Google Services for Push Messaging
or use brave://settings/privacy shortcut.
My problem was actually in my settings for Chrome. Under Content Settings, Notifications was set to Do not allow any site to show notifications. Changing this setting to Ask when a site wants to show notifications resolved the issue for me.
DOMException occurs when an operation is impossible to perform, either for logical reasons, because data is lost, or because the implementation has become unstable. You got your error DOMException: Registration failed - permission denied maybe because the manifest was loaded from a different domain than the main page. Suggested from this thread, try to use <link rel="manifest" href="/manifest.json"> if your page is not located at the root of the website. You can also check on this related SO question.

Unable to run pushtest Apigee sample

I am trying to run the pushtest sample that ships with the iOS SDK. In the .m file I have replaced the org name, app name and notifier name( which I have named 'apple'). I have the provisioning set up for my iPad. When I run the code, I don't see any window asking me to allow push notifications. On clicking the push to this device, the terminal spits out this error:
2014-01-30 14:04:20.525 Push Test[2970:60b] displaying alert. title: Error, message: {"error":"unauthorized","timestamp":1391119457656,"duration":0,"exception":"org.apache.shiro.authz.UnauthorizedException","error_description":"Subject does not have permission [applications:post:ed031740-7e90-11e3-a906-25e89414fcd7:/notifications]"}
I believe this is because the app has not obtained push permission, however, the alert window asking for this was not presented in the first case. How can I fix this?
"error":"unauthorized"`
This is an indication that your request requires authentication and you're not authorized to access the endpoint.
Push notifications out of the box require authentication - either an access_token (recommended) or client_id/secret. Try including the access_token in your header (instructions here).
If you want to disable authentication, you can add the GUEST role to /notifications (instructions here).
You need to give permissions to your application role:
curl -X POST "https://api.usergrid.com///roles/ -d '{"name":"nameforrole","title":"titleforrole","permission" : "GET,PUT,POST,DELETE:/users/me/**"}'

Can I request scripts for use in a Spotify app?

I'm trying to use socket.io in my spotify app and the get request for [domain]/socket.io/socket.io.js keeps getting canceled. I've added the domain to the manifest and everything.
Thanks!
Try restarting Spotify. Your app's manifest.json file is loaded when you first view your app, and cached until you quit, even if you modify it.
Note: How external resource permissions work
In order to request external resources, your application needs to specify each domain it plans to connect to in its manifest.json file.
Add a line like this:
{
// ...
"RequiredPermissions": [ "http://*.spotify.com", "http://spotify.com", "http://test.example.com" ]
// ...
}
For the full details check out the Permissions section of the Spotify Apps API Guide.
I can add that when you use socket.io it will try to initialize Flash to check if flash is available so if you find a white box in Spotify (only in Windows), remove the swbobjects initialization in the socket.io.js on the node server.

Resources