Is there any way to get project-id in google cloud endpoint? - google-cloud-endpoints

I just want my project-id in the endpoint. Is there any way to get directly or I have to open app.yaml in endpoint?

I solved this using
APP_ID = str(os.getenv('APPLICATION_ID'))
APP_VERSION = float(os.getenv('CURRENT_VERSION_ID'))
APP_VERSION = int(APP_VERSION)

Related

Getting "Missing or malformed Token" while using gofiber firebase-auth

I am trying to run Gofiber firebase-auth. I have generated a private key from Firebase Console, Settings -> Service Account -> Generate new private key and have given the file path to:
.env:
GOOGLE_SERVICE_ACCOUNT = 'C:/Users/Desktop/flutter-demo.json'
WEB_API_KEY = "<API_KEY>" // from config section of general settings at firebase console
TEST_USER_EMAIL = "test#test.com"
TEST_USER_PASSWORD = "test123"
which is used in main.go:
serviceAccount, fileExi := os.LookupEnv("GOOGLE_SERVICE_ACCOUNT")
opt := option.WithCredentialsFile(serviceAccount)
But, on accessing any of the Authenticated Routes, I'm getting:
Missing or malformed Token
Can anyone please help, maybe I'm doing some mistake or missing something from the docs
Hi below is an example of using gofiber firebase auth,
https://github.com/gofiber/recipes/tree/master/firebase-auth
Hope this will help you. Thanks
Thanks to Sachintha, one needs to send an Authorization Header token from login with the user name and password, as go firebase auth just a middleware to check whether endpoints are authenticated and it does not provide any authentication or user login.

Send firebase storage authorization as url parameter from a flutter web app

I would like to know how to make an authorized request to firebase storage using the user Id Token as a parameter in the url. Right now with a firebase rule of 'request.auth != null' I receive a 403 network error (Failed to load video: You do not have permission to access the requested resource). Here is my GET request url:
https://firebasestorage.googleapis.com/v0/b/<bucket>/o/<folder_name>%2F<video_name>.mp4?alt=media&auth=eyJh...<ID TOKEN>...Ll2un8ng
-WITHOUT the firebase rule in place I'm able to successfully get the asset with this request url https://firebasestorage.googleapis.com/v0/b/<bucket>/o/<folder_name>%2F<video_name>.mp4?alt=media
-also tried token=, token_id=, tokenId=
-the reason for not using the firebase SDK to fetch the file is so that I can use the flutter video_player (https://pub.dev/packages/video_player#-example-tab-) package and use this with files in firebase, I mention this in case theres a better way to use the video_player library in flutter web right now:
_controller = VideoPlayerController.network(
'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4',
closedCaptionFile: _loadCaptions(),
);
[EDIT] It appears that it's not possible to pass the auth in as a query parameter. After some exploring, I found an acceptable way to still use the video_player with your firebase assets that are protected (If you're not using rules to protect them, you can directly use the firebase url). I will post some general steps here and some sample code:
Use the Storage Firebase SDK package to get the Uint8List, the uri given by getDownloadURL has the correct header auth, for example
import 'package:firebase/firebase.dart';
final url = await storagePath.getDownloadURL();
final response = await http.get(url);
if (response.statusCode == 200) {
return response.bodyBytes;
}
use the Uint8List buffer to init a Blob object which you'll use to then create an ObjectURL which basically gives you the same interface as a file url to use as the network url for your video player
final blob = html.Blob([data.buffer], 'video/mp4');
final videoUrl = html.Url.createObjectUrl(blob);
videoPlayerController = VideoPlayerController.network(
videoUrl)
..initialize().then((_) {...
That's it.
Firebase Storage REST does not (rightly) support authorization from GET query string as you are trying to do. Instead, it uses the standard Authorization header (see here).
Firebase cloud storage internally uses Google Cloud Storage. Mentioned here
If the library you use doesn't support HTTP headers yet, you must consider an alternative. The issue you mentioned in the comment shows that the feature is still under development, so you can also wait for the library to come out with the support for headers.
Internally all this package does for flutter-web is create an HtmlElementView widget here for which it passes a VideoElement (ref here) from the package dart:html with the provided URL which translates to a <Video> tag inside a shadow dom element in your web page. The error 403 could also mean you are trying to access it from a different origin.
I would suggest following approach.
Check your console for any CORS related errors. If yes, then you will have to whitelist your ip/domain in the firebase storage. Check this post for possible approach and more details here.
Check if you are able to access the URL directly with the authorization token as a query parameter as you suggested. If not then, it is not the correct way to access the object and should be corrected. You could update the question with the exact error details.

Firebase Storage REST API

I need very simple static image server for my flutter app. I am thinking about Cloud Storage, because I don't want to worry about own server administrating. I am using experimental Flutter for Desktop as tool for preparation data for mobile app, so I can use only REST API. I found out that Firebase Storage doesn't have own REST API and uses Google Cloud's one. To upload image to Cloud Storage I should make something like this:
curl -X POST --data-binary #[IMAGE_LOCATION] \
-H "Authorization: Bearer [OAUTH2_TOKEN]" \
-H "Content-Type: image/jpeg" \
"https://www.googleapis.com/upload/storage/v1/b/[BUCKET_NAME]/o?uploadType=media&name=[IMAGE_NAME]"
The problem is I can't understand how to get [OAUTH2_TOKEN] (access token) from my Dart code, and how to administrate my images (should I do something with Firebase Admin SDK?)
Could anyone help me, please?
I found answer to this question. First you need to create private key for service account in Firebase settings. Then use it to get access token using dart packages googleapis_auth and http.
var accountCredentials = ServiceAccountCredentials.fromJson({
"private_key_id": "<please fill in>",
"private_key": "<please fill in>",
"client_email": "<please fill in>#developer.gserviceaccount.com",
"client_id": "<please fill in>.apps.googleusercontent.com",
"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;
File image = File('path/to/image');
var request = Request(
'POST',
Uri.parse('https://storage.googleapis.com/upload/storage/v1/b/[BUCKET_NAME]/o?uploadType=media&name=images/$imageName'),
);
request.headers['Authorization'] = "Bearer $accessToken";
request.headers['Content-Type'] = "image/jpeg";
request.bodyBytes = await image.readAsBytes();
Response response = await Response.fromStream(await request.send());
print(response.statusCode);
client.close();
Get request you can make the similar way, but you have to encode firebase path to image:
var imagePath = 'images/img.jpg';
var encodedImagePath = Uri.encodeQueryComponent(imagePath);
var request = Request(
'GET',
Uri.parse('https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]/o/$encodedImagePath?alt=media'),
);
request.headers['Authorization'] = "Bearer $accessToken";
Google Cloud REST API: https://cloud.google.com/storage/docs/downloading-objects
The Firebase Storage REST API allows you to upload and download files from Cloud Storage using HTTP requests. You can use this API to build server-side applications that interact with Cloud Storage, or to integrate Cloud Storage into your existing server-side application.
To use the Firebase Storage REST API, you will need to have a Firebase project and a Cloud Storage bucket set up. You can set up a new Firebase project and Cloud Storage bucket by following the instructions in the Firebase documentation.
Once you have a Cloud Storage bucket set up, you can use the following HTTP methods to access and manipulate files in your bucket:
POST: To upload a new file to Cloud Storage, you can send a POST request to the /upload endpoint, along with the file data in the request body.
GET: To download a file from Cloud Storage, you can send a GET request to the /download endpoint, specifying the file's path in the bucket as a query parameter.
DELETE: To delete a file from Cloud Storage, you can send a DELETE request to the /delete endpoint, specifying the file's path in the bucket as a query parameter.
To authenticate your requests to the Firebase Storage REST API, you will need to provide a valid Firebase Authorization header with each request. You can generate this header using a JSON service account key file, which you can obtain from the Firebase console.
For more information about using the Firebase Storage REST API, including examples of how to make requests and handle responses, you can refer to the Firebase Storage REST documentation.
I hope this helps!

what the $resourceURI should be?

We have an azure webapp which is configured Managed Service Identity. We also have a keyvault which we configured with some secrets. The Managed Service Identity account was granted access to the keyvault. I'm basically trying to validate the webapp can connect to the keyvault and read the secrets. I found the below powershell examples but I'm not following what the $resourceURI should be. Is that the webapp?
$apiVersion = "2017-09-01"
$resourceURI = "https://<AAD-resource-URI-for-resource-to-obtain-token>"
$tokenAuthURI = $env:MSI_ENDPOINT + "?resource=$resourceURI&api-version=$apiVersion"
$tokenResponse = Invoke-RestMethod -Method Get -Headers #{"Secret"="$env:MSI_SECRET"} -Uri $tokenAuthURI
$accessToken = $tokenResponse.access_token
Since you need a token for Key Vault, $resourceURI should be https://vault.azure.net/
Feel free to check out our tutorials at: aka.ms/azuremsi
Hope this helps.
-Arturo

Calling google cloud endpoint api from another google app engine web application servlet java

I have a google cloud endpoint api application which i want to call it from another google app engine web application, say from a servlet. The cloud endpoint api is not secured.
I tried looking for examples but could not find one. I see example related to Android client.
When tried using URLConnection it does not work, am not sure whether am doing correctly as well, sample codes or pointers will be of great help. I also checked the logs of cloud endpoint api to see if any requests are coming through, but i don't see any errors in the logs.
I'm doing this as well, although with authentication. You can use the Jar generated by the endpoint API at MyAPI/build/libs/MyAPI-v1-SNAPSHOT.jar, just as you might in Android.
Once you depend on that JAR, your code to build an API client should look something like that below. Mine is using OAuth authentication with a service account, which I'll leave in there because it was the more complicated part which you might eventually need. But without authentication you should just be able to set the credential to null.
HttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
List<String> SCOPES = Arrays.asList(EMAIL_SCOPE);
String SERVICE_ACCCOUNT_ID = "my-account-id#my-app.iam.gserviceaccount.com";
String CREDENTIAL_FILE = "WEB-INF/my-file.p12";
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCCOUNT_ID)
.setServiceAccountScopes(SCOPES)
.setServiceAccountPrivateKeyFromP12File(new File(CREDENTIAL_FILE))
.build();
MyAPI.Builder builder = new MyAPI.Builder(
HTTP_TRANSPORT,
JSON_FACTORY, credential)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://localhost:8080/_ah/api/")
// .setRootUrl("https://my-appengine-url.appspot.com/_ah/api")
MyAPI myAPI = builder.build();
You cannot use URLConnection for making endpoint calls from App Engine. Use FetchURL instead. If you set doNotFollowRedirect, you will receive X-Appengine-Inbound-Appid as header in the called App Engine project. You can trust this header, as Google would strip it off if somebody off App Engine would use it. Make sure you target the yourproject.appspot.com domain, as it won't work with custom domains.
https://cloud.google.com/appengine/docs/java/appidentity/

Resources