Error while using FIREBASE STORAGE in flutter using HTTP REST api - firebase

I am getting the error while inserting image file into the firebase Stroage. I am using HTTP rest api's for the same.
The code is as follows:
Future<void> upload(Image image2) async {
var accountCredentials = ServiceAccountCredentials.fromJson({
"private_key_id": " ",
"private_key": " ",
"client_email":"< >.iam.gserviceaccount.com",
"client_id": "",
"type": "service_account"
});
var scopes = [
'https://www.googleapis.com/auth/cloud-platform',
];
var client = Client();
AccessCredentials credentials =
await obtainAccessCredentialsViaServiceAccount(accountCredentials, scopes, client);
String accessToken = credentials.accessToken.data;
var request = Request(
'POST',
Uri.parse(
'https://www.googleapis.com/upload/storage/v1/b/mybucket/o?uploadType=media&name=$image2'),
);
request.headers['Authorization'] = "Bearer $accessToken";
request.headers['Content-Type'] = "image/png";
Response response = await Response.fromStream(await request.send());
print("response is ");
print(response.statusCode);
print("response body");
print(response.body);
client.close();
}
The Error is as follows:
{
"error": {
"code": 403,
"message": "< >.iam.gserviceaccount.com does not have storage.objects.create access
to the Google Cloud Storage object.",
"errors": [
{
"message": "< >.gserviceaccount.com does not have storage.objects.create access to the
Google Cloud Storage object.",
"domain": "global",
"reason": "forbidden"
}
]
}
}
I have given the permission of storage.objects.create through IAM service management but this is not working
Click here to view ScreenShot of assigned permission

Related

Firebase login with email link fails with code 400 OPERATION_NOT_ALLOWED

I configured email with passwordless login in my Firebase project
And followed the documentation at https://firebase.google.com/docs/auth/web/email-link-auth
My code:
const actionCodeSettings = {
url: "https://acme.com",
handleCodeInApp: true,
dynamicLinkDomain: "acme.com",
};
const response = await firebase.auth().sendSignInLinkToEmail(email, actionCodeSettings);
Which translates to the following request:
curl 'https://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=XXX' \
...
--data-raw '{"requestType":"EMAIL_SIGNIN","email":"mugen#acme.co","continueUrl":"https://acme.co","canHandleCodeInApp":true,dynamicLinkDomain:"acme.com"}'
And I get the following response:
{
"error": {
"code": 400,
"message": "OPERATION_NOT_ALLOWED",
"errors": [
{
"message": "OPERATION_NOT_ALLOWED",
"domain": "global",
"reason": "invalid"
}
]
}
}
The domain is in the authorized list. I tried with and without sending the dynamicLinkDomain parameter.
Actually, I faced same problem.
https didn't work, but http worked.
const actionCodeSettings = {
url: "http://acme.com",
handleCodeInApp: true,
dynamicLinkDomain: "acme.com",
};

How to extract data from response params in the custom identity provider

Since the latest maintenances from ConnectyCube servers, I am experiencing a new issue when I authenticate with the custom identity provider.
I use Firebase as endpoint and it return the following json file (tested with Postman) :
{
"kind": "identitytoolkit#GetAccountInfoResponse",
"users": [
{
"localId": "The uid that I want to get",
"email": "test#test.com",
"passwordHash": "xxxxxx",
"emailVerified": false,
"passwordUpdatedAt": 1607681539305,
"providerUserInfo": [
{
"providerId": "password",
"federatedId": "test#test.com",
"email": "test#test.com",
"rawId": "test#test.com"
}
],
"validSince": "1607681539",
"disabled": false,
"lastLoginAt": "1620422687374",
"createdAt": "1607681539305",
"lastRefreshAt": "2021-05-07T21:24:47.374Z"
}
]
}
Previously, to get the localId, I used the following as responses params {"uid": "#{users[0].localId}"} and it worked.
Now I get the error "base":["Custom Identity Provider uid is required"] when I try to sign in the users while nothing changed in my code.
Do you have a solution to access to the localID parameter without using [0] as it seems to be the cause of the issue?
My current settings for the custom identity provider:
ENDPOINT: https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=API_WEBKEY
REQUEST HEADERS: {"Content-Type": "application/json"}
REQUEST PARAMS: {"idToken": "#{login}"}
RESPONSE PARAMS: {"uid": "#{users[0].localId}"}
Extract of my script where the error appear:
final token = await FirebaseLib().auth.currentUser.getIdToken();
createSession().then((cubeSession) {
CubeUser user = CubeUser(login: "$token", password: "");
signIn(user).then((cubeUser) {
Print("Worked!");
}).catchError((error) {});
}).catchError((error) {});
This should work now again
Please check

FirebaseAdmin messaging returning 404 not found

I am writing an API that sends an firebase message (using the official FirebaseAdmin library) when requested to a android device. I got it working perfect in normal C#, but in ASP.NET core I always get a 404 not found exception.
Response status code does not indicate success: 404 (NotFound)
{
"error": {
"code": 404,
"message": "Requested entity was not found.",
"errors": [
{
"message": "Requested entity was not found.",
"domain": "global",
"reason": "notFound"
}
],
"status": "NOT_FOUND"
}
}
I run the following code at startup:
if (FirebaseApp.DefaultInstance == null)
{
FirebaseApp.Create(new AppOptions
{
Credential = GoogleCredential.FromFile($#"{env.WebRootPath}\app-5a821-firebase-adminsdk-pf36f-6f44114d87.json")
});
}
And this is the request that I made, very simple:
[HttpGet]
public async Task<ActionResult<IEnumerable<string>>> Get()
{
var message = new Message
{
Token = "dgY8UMXhEZ4:APA91bFnrZTGJKkCCBJHzbghvsvEaq-w-ee1XBAVqAaS-rsmR3Ald23rHGgpfdgVb09r97jDQBVSc6GtDHWtLHWAnn4Lm3EM_j-sh7cu-RaRSrfnk3X124v4co3Q9ID6TxFdGgv7OXWt",
Data = new Dictionary<string, string>
{
{"title", "test" }
}
};
try
{
var fcmResult = await FirebaseMessaging.DefaultInstance.SendAsync(message);
} catch (FirebaseException ex)
{
}
return new string[] { "value1", "value2" };
}
Github test project: https://github.com/kevingoos/FirebaseAdminTest
Solved problem: https://github.com/firebase/firebase-admin-dotnet/issues/73
This happens when the token is invalid/expired or does not belong to the same project as the credentials used to initialize the Admin SDK.

How to get permissions / scope for Google Apps Script to Firebase Cloud Messaging HTTP v1 API?

I am trying to send a Firebase Cloud Message from Google Apps Script. I have followed the following questions & links & assembled the following code:
Get 403 response with the "new" Firebase Cloud Messaging API
The res|error I am receiving is:
{
"error": {
"code": 403,
"message": "Request had insufficient authentication scopes.",
"status": "PERMISSION_DENIED"
}
}
My Code in Google Apps Script is:
function sendFCM(text){
text = {
"message": {
"topic": "news",
"notification": {
"title": "Breaking News",
"body": "New news story available."
},
"data": {
"story_id": "story_12345"
}
}
}
var projectId = "xxxxxxx";
var apiUrl = "https://fcm.googleapis.com/v1/projects/"+projectId+"/messages:send";
var authKey = "AAAU.......Cs";
var token = ScriptApp.getOAuthToken();
var options = {
'method' : 'post',
'contentType': 'application/json',
'muteHttpExceptions' : true,
'payload' : JSON.stringify(text),
headers:{Authorization: "Bearer "+ token},
};
var res = UrlFetchApp.fetch(apiUrl, options);
Logger.log(res);
}
Script's properties > User Scopes list follwoing:
https://www.googleapis.com/auth/firebase.database
https://www.googleapis.com/auth/script.external_request
https://www.googleapis.com/auth/spreadsheets
https://www.googleapis.com/auth/userinfo.email
FCM & GCM Api is enabled in project's developer console.
Edit:
From Ref's comment, I added the following scope to app manifest:
https://www.googleapis.com/auth/firebase.messaging
Upon Run, it asked me to authorize & now the response is an instance of a Message. But still I do not know how to define a to device i.e. to which device the message should go.
{
"name": "projects/send-xxxx3/messages/866xxxxx92"
}

Failed to fetch events (404) from Google+ Calendars after OAuth 2.0 for limited devices

I'm writing a watchapp for Pebble to show events from the Google calendars.
I'm using Auth 2.0 to authenticate the user as described in this document.
Then I retrieve events using this API v3 call, specifying my access_token in the authorization header.
For the calendars created and managed by the user everything works fine.
However if I try to get the events from the Google+ calendars, such as Birthdays (#contacts#group.v.calendar.google.com) or Holidays in Italy (en.italian#holiday#group.v.calendar.google.com), the answer is 404:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "notFound",
"message": "Not Found"
}
],
"code": 404,
"message": "Not Found"
}
}
What am I doing wrong? Or is it a bug of the Calendar API?
Thanks to luc, here's the answer!
I was calling the service this way:
var GET_EVENT_LIST = "https://www.googleapis.com/calendar/v3/calendars/%s/events";
var calendarId = "#contacts#group.v.calendar.google.com";
var token_type = "Bearer";
var access_token = "...";
var url = sprintf(GET_EVENT_LIST, calendarId);
var req = new XMLHttpRequest();
req.open("GET", url, true);
req.setRequestHeader("Authorization", token_type + " " + access_token);
req.send(null);
I solved changing the fifth line to:
var url = sprintf(GET_EVENT_LIST, encodeURIComponent(calendarId));

Resources