How to setup google service account authorization in Node.js with JSON key file? - google-api-nodejs-client

Trying to make use of the Server to Server OAuth flow defined here:
https://developers.google.com/identity/protocols/OAuth2ServiceAccount
Since I'm running from a local dev environment, I've created a service account in GCP and downloaded the JSON file with the private key, but cannot find any Node.js code examples on how to:
1) load the json file
2) set delegated credentials (for G Suite domain-wide authorization)
Places I've looked (besides stackoverflow) are Google's git wiki for the node.js client library, which does talk about server to server auth, but seems to assume you're running from appengine or google cloud and don't need to load a key file:
https://github.com/googleapis/google-api-nodejs-client#service-to-service-authentication
The Admin SDK Activities Reports API has a Node example, but it's using the web-based flow assuming a user is present:
https://developers.google.com/admin-sdk/reports/v1/quickstart/nodejs
Buried deep in the Node.js samples is use of the Directory API, which does seem to take a keyfile as input, but when I try running locally it says getClient is not a constructor, and still this example doesn't show how to set the G Suite admin user for context (which is generally when a refresh token and access token are loaded into the app):
https://github.com/googleapis/google-api-nodejs-client/blob/master/samples/directory_v1/group-delete.js
So... does anybody have an example of this? I really don't want to switch to a Python runtime but Google seems to have left out important examples on this topic.

Related

How to auth google cloud API from Java in the same way I authenticated with gcloud CLI

Using gcloud command line I can do the following operation
gcloud builds describe 74f859e9-d621-4632-b6dd-XXXXXXXX
However I wish to use the Google Cloud API from Java, now as I understand the GCloud CLI is not using a service account, it is using a user account. How can I use the same authentication from Google Cloud Java API to do this same operation to describe a build?
Google provides decent documentation that explains how to use its SDKs (Client Libraries) with all of its services.
Here's the Cloud Build client libraries documentation. Pick your preferred language and go.
If you can't use one of Google's SDKs, then you can write code directly against the underlying API. Google's APIs Explorer is an excellent tool for navigating all Google's services. Here's Cloud Build and projects.builds.get which I think (!?) maps to gcloud build describe. You can confirm that by running gcloud builds describe --log-http to see which underlying calls are made.
Code that doesn't access user data (data owned by a user account), should run as a Service Account. Code that accesses user data or operates on behalf of a user, should use the OAuth flow for the user and use an OAuth Client ID. This is what gcloud does. As a program operating on behalf of users, it authenticates you the user using a regular OAuth flow but it operates using an OAuth Client ID against a hidden backing project. Your code should probably just run as a service account.

Retrieve logged user information from cloud foundry web application

We developed a web application using SAP Web-IDE Full Stack; we need to retrieve the details of the user logged into application (as defined in SAP Cloud Platform Identity Authentication Administration), for example display name and assigned groups.
We tried the userapi/currentUser API, but it seems to work only on NEO environment, for this reason is working fine while debugging in Web-IDE, but we get a 404 error when deploying the app on Cloud Foundry.
Do we need to add a new destination to make userapi work also on CF? Or is there some kind of similar solution available on Cloud Foundry?
I highly suggest using the SAP S/4HANA Cloud SDK for such tasks. It is an SDK developed to make building applications for SAP Cloud Platform easy, by providing easy to use mechanisms for all the Cloud Platform mechanisms.
Regarding your task at hand, there is a UserAccessor class that you can use like this:
final Optional<User> user = UserAccessor.getCurrentUser();
This works on Neo as well as on Cloud Foundry, i.e. there is a single interface for both platforms, which allows you to develop your app in a platform agnostic way.
If this sounds like it could solve your problem, I recommend checking out this blog post series to get started.
Alternatively, you can also simply add the following dependency to your project to start testing the SDK:
<dependency>
<groupId>com.sap.cloud.s4hana.cloudplatform</groupId>
<artifactId>scp-neo</artifactId>
<version>2.7.0</version>
</dependency>
For Cloud Foundry use scp-cf instead of scp-neo.
Hope this helps!
P.S.: To answer your question also on a technical level, Cloud Foundry uses so-called JWTs for authentication and authorization. You can check whether a JWT is present by looking at the Authorization header of the request. The JWT should hold the information you're looking for.
In SAP Cloud Foundry if you develop a MTA using XSUAA service to manage User Authentication and Admistration, defined for example in the mta.yaml,
...
resources:
- name: uaa_myapp
parameters:
path: ./xs-security.json
service-plan: application
service: xsuaa
type: org.cloudfoundry.managed-service
...
you can use the UAA API published from XSUAA service self to manage user authentication and authorization (e.g.: retrieve user info, groups assigned, password management etc..). also in the case the application is federated with another IDP.
To consume this API for example to retrieve user info you need to:
Determine the XSUAA endpoint bound to your app (SCP Cockpit > XSUAA service detail > take the value url)
Create a destination (xsuaa_api_destination) of type OAuth2TokenExchange bound to your app with url url took before, and fill OAuth2 authentication parameters with the data contained in XSUAA service detail (step 1).
From your app execute the call xsuaa_api_destination/userinfo, for example using an ajax if you are using JS.
You can find other info in Account and Authentication Service of the Cloud Foundry Environment SAP doc.

Response status code does not indicate success: 401 (Unauthorized) When calling Azure Blockchain RESTApi

Response status code does not indicate success: 401 (Unauthorized) When calling Azure Blockchain
I am getting above error when calling Azure Blockchain RESTApi and I have checked all the permissions and getting Access Token correctly but When I call to get the applications we are getting Above mentioned Error
The issue was fixed, by following the below steps:
1) Go to Azure Portal-> App Service -> [Your App Service]-Api
2) Go to Authentication/Authorization Blade
Allow App Service Authentication and choose Allow anonymous requests(no action) and choose Azure Active Directory as Authentication Providers
Click on Advanced -> Fill in the options as in the following image:
Client ID is the same as App ID in the AzureAD Application Registration
Client Secret is the same as API Key you generated from the Keys Section in the AzureAD Application Registration
Issuer URL is https://sts.windows.net/{AZUREADTENANTID} ß You can get the azuread tenant ID from the AzureAD Properties
Allowed Token Audiences should have the following value:
i. [https://%7bYOURBLOCKCHAINAPIURL-API.azurewebsites.net/.auth/login/aad/callback]
https://{YOURBLOCKCHAINAPIURL-API.azurewebsites.net/.auth/login/aad/callback
3) Go to Azure Active Directory
Now, go to Azure AD and Navigate to App Registrations and Click BlockChain API ß or the name you chose for your Azure AD App Registration when you configured blockchain the first time:
Click Settings and Click Reply URLs
Add the following URLs there:
Blockchain Workbench URL (it should be already there)
Blockchain API Base URL (the one that has -API in it)
Blockchain API Base URL with Callback (as indicated below, but use your own URL and add /.auth/login/aad/callback)
The getpostman.com/oauth2/callback URL will be used later to test the API using the Postman App (An App used to test APIs), please add it as is below
4) Save your settings and then go to the Manifest(Next to settings in the Blockchain API AzureAD App Properties)
Set the manifest entry oauth2allowimplicitflow to True
Save Configuration.
That’s it, now we need to test the API, you can download Postman to test the API, the configuration of Postman is a little bit long, I would prefer that you sign up free on this service: https://www.wintellectnow.com/Videos/Watch?videoId=blockchain-on-azure
Use Code: FREETRIAL to sign up – It will require a credit card but it won’t be charged, use any prepaid or postpaid card, but watching this video is highly recommended, specially at minute 53 as it explains how to use the API with Postman (Remember to disable the trial to prevent the card from being charged after 7 days 😊)
Here is a sample Token generated using the built in Auth Sample code that comes with Azure Blockchain Samples on Gethub (You can download this from here: https://github.com/Azure-Samples/blockchain/tree/master/blockchain-workbench/auth-samples/bearer-token-retrieval/static ), if you are going to test using it, you must add http://localhost to the Reply URLs above and you have to place it on your localhost IIS)
And here is a sample from Postman which shows how the token is added to the request header:
Here is the response before the authorization token:
Once the authorization token is available, here is the response that is generated once I call the API indicated in the GET Section in the image above:
Also, here is the response headers after a successful authorization:
To sum it up, the #blockchain API requires #OAuth2 authentication token, this token isn’t passed using Swagger UI or the application you built, you need to modify your application to authenticate to AAD OAuth2 to obtain a Token from AzureAD, then you need to use this generated token in the request header to the API in order to call the API.
One additional tip, don’t select the default machine size while creating workbench, but choose better performance machines like: VM Size: Standard F2s_v2 (2 vcpus, 4 GB memory) ==> approx.. 50 USD per month .
Discussion on Microsoft tech community site
The original Post of the Author
We are currently experiencing an outage in South Central US
https://azure.microsoft.com/en-us/status/
Azure AD is also impacted.
You will want to monitor the Azure Status Page for further updates. Unfortunately we cannot do anything until the problem has been mitigated by engineering.
After the issue has been mitigated and if you are still seeing issues let us know.

Google Cloud Storage 500 Internal Server Error 'Google::Cloud::Storage::SignedUrlUnavailable'

Trying to get Google Cloud Storage working on my app. I successfully saved an image to a bucket, but when trying to retrieve the image, I receive this error:
GCS Storage (615.3ms) Generated URL for file at key: 9A95rZATRKNpGbMNDbu7RqJx ()
Completed 500 Internal Server Error in 618ms (ActiveRecord: 0.2ms)
Google::Cloud::Storage::SignedUrlUnavailable (Google::Cloud::Storage::SignedUrlUnavailable):
Any idea of what's going on? I can't find an explanation for this error in their documentation.
To provide some explanation here...
Google App Engine (as well as Google Compute Engine, Kubernetes Engine, and Cloud Run) provides "ambient" credentials associated with the VM or instance being run, but only in the form of OAuth tokens. For most API calls, this is sufficient and convenient.
However, there are a small number of exceptions, and Google Cloud Storage is one of them. Recent Storage clients (including the google-cloud-storage gem) may require a full service account key to support certain calls that involve signed URLs. This full key is not provided automatically by App Engine (or other hosting environments). You need to provide one yourself. So as a previous answer indicated, if you're using Cloud Storage, you may not be able to depend on the "ambient" credentials. Instead, you should create a service account, download a service account key, and make it available to your app (for example, via the ActiveStorage configs, or by setting the GOOGLE_APPLICATION_CREDENTIALS environment variable).
I was able to figure this out. I had been following Rail's guide on Active Storage with Google Storage Cloud, and was unclear on how to generate my credentials file.
google:
service: GCS
credentials: <%= Rails.root.join("path/to/keyfile.json") %>
project: ""
bucket: ""
Initially, I thought I didn't need a keyfile due to this sentence in Google's Cloud Storage authentication documentation:
If you're running your application on Google App Engine or Google
Compute Engine, the environment already provides a service account's
authentication information, so no further setup is required.
(I am using Google App Engine)
So I commented out the credentials line and started testing. Strangely, I was able to write to Google Cloud Storage without issue. However, when retrieving the image I would receive the 500 server error Google::Cloud::Storage::SignedUrlUnavailable.
I fixed this by generating my private key and adding it to my rails app.
Another possible solution as of google-cloud-storage gem version 1.27 in August 2020 is documented here. My Google::Auth.get_application_default as in the documentation returned an empty object, but using Google::Cloud::Storage::Credentials.default.client instead worked.
If you get Google::Apis::ClientError: badRequest: Request contains an invalid argument response when signing check that you have dash in the project name in the signing URL (i.e projects/-/serviceAccounts explicit project name in the path is deprecated and no longer valid) and that you have "issuer" string correct, as the full email address identifier of the service account not just the service account name.
If you get Google::Apis::ClientError: forbidden: The caller does not have permission verify the roles your Service Account have:
gcloud projects get-iam-policy <project-name>
--filter="bindings.members:<sa_name>"
--flatten="bindings[].members" --format='table(bindings.role)'
=> ROLE
roles/iam.serviceAccountTokenCreator
roles/storage.admin
serviceAccountTokenCreator is required to call the signBlob service, and you need storage.admin to have ownership of the thing you need to sign. I think these are project global rights, I couldn't get it to work with more fine grained permissions unfortunately (i.e one app is admin for a certain Storage bucket)

how to get client_id and client_secret code in cloud foundry using api's

In cloud foundry how can I get the client_id and client_secret code.
This will be used in Basic authentication instead of passing the user and password for respective api calls
In general, this is something that you would get from your platform administrator. He or she would be able to provide you with a properly configured client id and client secret to fit your needs. If you are not the administrator, then you won't be able to do this.
If you are an administrator, read on. There are many existing client and secret pairs within a Cloud Foundry platform. It's also possible, and suggested, to create custom client and secret pairs for use with non-platform apps. You shouldn't use a platform client for your custom app, you should use your own custom client, that way if the client is compromised you can delete it or change the secret.
All of this, viewing & managing client data, is done through UAA, so I'd recommend starting with the docs on UAA. Make sure that you understand the concepts. You may even want to take a step further back and review concepts of OAuth2 as well. Understanding OAuth2 will make working with UAA much easier.
https://docs.cloudfoundry.org/uaa/uaa-overview.html
After that, you'll need the uaac (i.e. UAA client) installed.
https://github.com/cloudfoundry/cf-uaac
Once you're familiar with UAA & have the client installed, this doc on how to manage clients should provide you with instructions to view or create a new client.
https://github.com/cloudfoundry/uaa/blob/master/docs/Sysadmin-Guide.rst#manage-client-registrations
You will need admin role to be able to create a client or get its details.
Refer https://docs.cloudfoundry.org/api/uaa/version/4.7.1/index.html#clients to see various api to manage and create clients.
You can also use the uaa client to get the client details.
Refer https://docs.cloudfoundry.org/uaa/uaa-user-management.html for more info.