How to get access token programatically for GCP Compute API - google-app-engine

I need some help for access tokens in GCP. I am using Java as program language and I tried different approaches like:
https://cloud.google.com/iap/docs/authentication-howto
and https://developers.google.com/identity/protocols/OAuth2ServiceAccount#jwt-auth
I am using the second approach. Code snippet:
String privateKeyId = "my-private-key";
long now = System.currentTimeMillis();
String signedJwt = null;
try {
Algorithm algorithm = Algorithm.RSA256(null, privateKey);
signedJwt = JWT.create()
.withKeyId(privateKeyId)
.withIssuer("my-issuer")
.withSubject("my-subject")
.withAudience("https://www.googleapis.com/compute/v1/compute.machineTypes.list")
.withIssuedAt(new Date(now))
.withExpiresAt(new Date(now + 3600 * 1000L))
.sign(algorithm);
} catch (Exception e){
e.printStackTrace();
}
return signedJwt;
Then I perform get instances setting the returned token as Bearer authorization header but response is:
com.google.api.client.http.HttpResponseException: 401 Unauthorized
{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
With same credentials I am able to access the SDK.
Thanks!

As per #DalmTo, you should be using the client library for Java. This is the link to get you started.

Related

Read all Azure AD users with Graph

I'm trying to read all users from my Azure AD with Graph with the following method:
public void GetUsers() {
var confidentialClient = ConfidentialClientApplicationBuilder
.Create("my application id")
.WithTenantId("my tenant id")
.WithClientSecret("my application secret")
.Build();
var graphClient = new GraphServiceClient("https://graph.microsoft.com/beta", new ClientCredentialProvider(confidentialClient));
var request = graphClient.Users.Request().Filter("accountEnabled eq true");
var users = await request.GetAsync(); // throws exception!
}
When I execute request.GetAsync() I receive the following exception:
{
"error": {
"code": "Authorization_RequestDenied",
"message": "Insufficient privileges to complete the operation.",
"innerError": {
"date": "2021-08-26T14:25:27",
"request-id": "d2772ea1-a994-4f14-bfad-0baffc6d24d3",
"client-request-id": "my application id"
}
}
}
On Azure AD I created an application, and I added over "API permissions" these permissions Read.User.All and Read.User
Do I need another specific permission? It's coding error?
Please make sure permission type is "Application" and not "Delegated" and Status shows "Granted for "
If you see status as "Not granted" , click on "Grant admin consent"

Gmail Api problems

We are currently trying to create a tool in Google Apps Script using OAuth2 for Authentication. The script is supposed to use the GMail api to carry out some tasks such as moving labels from one account to another.
Documentation we have used says we need to create a service account with domain wide authority and create necessary components to allow it to work (i.e client_id and so on.. )
We are getting the error below is anyone able to help?
Code:
function getGmailService() {
return OAuth2.createService('GmailMigration:' + user_email)
// Set the endpoint URL.
.setTokenUrl('https://oauth2.googleapis.com/token')
.setAuthorizationBaseUrl(CREDENTIALS.auth_uri)
// Set the private key and issuer.
.setPrivateKey(CREDENTIALS.private_key)
.setIssuer(CREDENTIALS.client_email)
// Set the name of the user to impersonate. This will only work for
// Google Apps for Work/EDU accounts whose admin has setup domain-wide
// delegation:
// https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
.setSubject(CLIENT_EMAIL)
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getScriptProperties())
// Set the scope. This must match one of the scopes configured during the
// setup of domain-wide delegation.
.setScope('https://mail.google.com https://www.googleapis.com/auth/gmail.modify
https://www.googleapis.com/auth/gmail.labels https://www.googleapis.com/auth/gmail.insert
https://www.googleapis.com/auth/gmail.addons.current.message.action https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/gmail.addons.current.message.metadata https://www.googleapis.com/auth/gmail.metadata');
}
function reset() {
getGmailService().reset();
}
function run() {
var service = getGmailService();
if (service.hasAccess()) {
console.log({Service: service})
var url = 'https://gmail.googleapis.com/gmail/v1/users/{user_id}/labels/{message/label_id}?key='+CREDENTIALS.api_key;
var response = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
},
muteHttpExceptions: true
});
var result = JSON.parse(response.getContentText());
Logger.log(JSON.stringify(result, null, 2));} else {
Logger.log(service.getLastError());
}
}
Error:
{
"error": {
"code": 400,
"message": "Precondition check failed.",
"errors": [
{
"message": "Precondition check failed.",
"domain": "global",
"reason": "failedPrecondition"
}
],
"status": "FAILED_PRECONDITION"
}
}
Thanks

Alexa skill is giving 'There was a problem with the requested skill's response', can we change this message to custom message?

I am new to Alexa skill, and I am developing an Alexa skill, in my case there are scenario when I don't want to wait for http response to back and if my lambda timeouts due to delay in response from Http can I give a custom message in place of 'There was a problem with the requested skill's response'. My code is :
'ProtectArmIntent': function() {
if(checkAccessToken(this.event.session.user.accessToken)){
var data = {
mode: HUB_MODE.ARM,
regId: "null"
}
callAPI("post", API_COMMANDS.HUB_MODE, data, this.event.session.user.accessToken)
.then((body) => {
if(body.response.status === "SUCCESS"){
this.emit(':tell', messages.ARM.SUCCESSFUL);
} else {
this.emit(':tell', messages.ARM.FAILED);
}
})
.catch((err) => {
this.emit('SessionEndedRequest');
//errorHandler.call(this, err, messages.ARM.FAILED);
});
} else {
this.emit('LinkAccount');
}
},
and alexa simulator request:
"request": {
"type": "SessionEndedRequest",
"requestId": "amzn1.echo-api.request.67e1612e-f8a4-43f5-ab28-175ba7d7941f",
"timestamp": "2019-11-13T21:13:11Z",
"locale": "en-GB",
"reason": "ERROR",
"error": {
"type": "INVALID_RESPONSE",
"message": "An exception occurred while dispatching the request to the skill."
}
}
I know the issue is because lambda timeout as delay in the HTTP response, so can I give some customize message like Your command is accepted and it will be executed in some time.
Please please help, Thanks in advance
Making your own timer function might help. Set your timer lower than the lambda timeout and send your response at the end of the timer which will of course not lead to a lambda timeout error.This answer might help.

Unable to create Power Bi Datasource using API

I'm trying to create Power Bi data source following Microsoft provided documentation. But getting Bad Request DMTS_InvalidConnectionDetailsError error. Here is my post data sample.
{
"dataSourceType": "SQL",
"connectionDetails": "{\"Server\":\"MySqlServer\",\"Database\":\"MySqlDatabase\"}",
"datasourceName": "New Datasource",
"credentialDetails": {
"credentialType": "Basic",
"credentials": "{\"credentialData\":[{\"name\":\"username\", \"value\":\"MyUsername\"},{\"name\":\"password\", \"value\":\"MyPassword\"}]}",
"encryptedConnection": "Encrypted",
"encryptionAlgorithm": "RSA-OAEP",
"privacyLevel": "None"
}
}
And here is the response json.
{
"error":
{
"code": "DMTS_InvalidConnectionDetailsError",
"pbi.error": {
"code": "DMTS_InvalidConnectionDetailsError",
"parameters": {},
"details": [],
"exceptionCulprit": 1
}
}
}
Anybody can help please?
The credentials from credential details need to be encrypted using the RSA algorithm before passing it to the API. You can use the algorithm from https://learn.microsoft.com/en-us/power-bi/developer/encrypt-credentials. Also, the name of the server needs to have double the amount of "\" characters if it has any.

Gmail API watch request not working properly

There are many post on this same topic but still there is no exact solution to solve this issue.
even in the google API below link, there is a option to test the API
https://developers.google.com/gmail/api/v1/reference/users/watch
This API throws a error like Invalid Topic Name does not match but I have created the topic in the pub sub and I have published the message on it, that topic works fine but then also I am receiving below error. I am receiving 400 error
{ "error": {"errors": [{
"domain": "global",
"reason": "invalidArgument",
"message": "Invalid topicName does not match projects/google.com:apisexplorerconsole/topics/*" } ],"code": 400,"message":"Invalid topicName does not match projects/google.com:apisexplorerconsole/topics/*" }}
I have tried to call this API in client side, like below
gapi.client.gmail.users.watch({
'userId': 'me',
"topicName": "projects/fast-metric-178608/topics/Test"
}).then(function (response) {
console.log(response)
});
Below is output , i am receiving 403 error
{ "error": { "errors": [{
"domain": "global",
"reason": "forbidden",
"message": "Error sending test message to Cloud PubSub projects/fast-metric-178608/topics/Test : User not authorized to perform this action."} ],"code": 403, "message": "Error sending test message to Cloud PubSub projects/fast-metric-178608/topics/Test : User not authorized to perform this action." }}
https://console.cloud.google.com/cloudpubsub/topicList
select your topic and
set your topic PERMISSIONS allUser and Select a role Pub/Sub Admin

Resources