Error consuming customerLicense App Marketplace with Service Account OAuth2 - google-apps

SOLUTION
I figured out how to solve this problem.
First of all here is my implementation with Service Account:
// Build service account credential.
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Collections.singleton("https://www.googleapis.com/auth/appsmarketplace.license"))
.setServiceAccountPrivateKeyFromP12File(new File("/path/to/mykey/key.p12"))
// .setServiceAccountUser("NOT SET THIS LINE")
.build();
License build = new License.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName("My Application").build();
Licenses execute = build.customerLicense().get("9999999999", "domain.test.com").execute();
This License Builder object is myself implementation based on the new google-api-client 1.17 and above. If someone could advice me how can i share with the rest of the community i will be glad to do it.
Best,
I have posted another thread, Google Apps Marketplace API customerLicense with OAuth2, explaining about my intentions to consume this API with OAuth2 Service Account strategy.
I have tried every method and officials library present and I always get Invalid OAuth header message or UNLICENSED
I am going to detail what is the scenery and what things i have tried:
I have and Google App Marketplace which use Service Account OAuth2 because all task are being perform on background.
This API Project has Service Account keys and Client Web Account keys too.
I published app restricted for my domain only because i am yet developing. So I installed App for my domain.
At this point it is suppose if I queried Customer License with API Project ID and Customer Id, which is domain name, I have to see the APP LICENSE for my domain.
I have used this jars https://developers.google.com/google-apps/marketplace/v2/developers_guide to access License API.
This is my code:
String appName = "MY APP";
AppsMarketService service = new AppsMarketService();
service.appId = "NUMBER_APP_ID";
service.appName = appName;
service.endpoint = "https://www.googleapis.com/appsmarket/v2/";
service.consumerKey = service.appId + ".apps.googleusercontent.com";
service.consumerSecret = "CLIENT_SECRET_FROM_WEB_OAUTH2_API_PROJECT";
service.authorize();
I get 403 forbidden if i use this code.
If i changed appId for prefix clientId from my API Project web OAuth2, I get 200 but with body UNLICENSED.
I have added scope to my app https://www.googleapis.com/auth/appsmarketplace.license and i still get the same result.
I have tried also getting Access Token from Admin user with Service Account handshake and then use that Oauth2 Access Token to access API License and the same result Invalid OAuth Token
My questions are:
Is there any way to access this API with Services Account keys, taking into consideration there is not consumer Secret in Service Accounts keys, only Client ID and private Key file?
Is there any updated library to use this with OAuth2 because i am seeing all this libraries are using OAuth1 with two-legged auth?
It would be great if someone can help me because we are trying to migrate our 7 Google App Old Marketplace Apps from OAuth1 to OAuth2 as per Google request but we have some black holes in our implementation if we would not be able to query what domains have our App Installed.
Best,

There is no need for any other libraries than OAuth2 lib. You can impmement this using urlfetch.
...
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.appengine.api.urlfetch.FetchOptions.Builder;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
...
String SERVICE_ACCOUNT_EMAIL = "...#developer.gserviceaccount.com";
String P12 = "...-privatekey.p12";
// appid is the same id that you have in the google cloud project that has the Google Apps Marketplace API and SDK enabled
String appid = "";
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(new NetHttpTransport())
.setJsonFactory(new JacksonFactory())
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Collections.singleton("https://www.googleapis.com/auth/appsmarketplace.license"))
.setServiceAccountPrivateKeyFromP12File(new File(P12))
.build();
credential.refreshToken();
String token = credential.getAccessToken();
URL url = new URL("https://www.googleapis.com/appsmarket/v2/licenseNotification/"+appid);
HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, Builder.allowTruncate());
request.setHeader(new HTTPHeader("Authorization", "Bearer "+token));
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
You need to install the OAuth2 package for this to work. In eclipse its under Google > Add Google Apis.

Related

token URL can't find

I have some problems with the Account Linking for Google Actions
I have implemented the OAuth2 steps described in the documentation by Google.
I have found out the client id and client secrete also authenticate my URL, but now I am stuck in token URL, what should I do in my PHP application that finds token, I am new to this I use web application to connect to smart home action

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.

GSuite : Client is unauthorized to retrieve access tokens using this method

Hi I'm trying to develop an for GSuite admin which enables to migrate their google drive data to another cloud service. But in the process of authentication i'm getting the below error.
{
"error": "unauthorized_client",
"error_description": "Client is unauthorized to retrieve access tokens using this method."
}
Below are the api's that are enabled in developer console.
1. Admin SDK
2. Contacts API
3. G Mail API
4. Calendar API
5. Drive API
Please guide me if done anything wrong in creating an app.
The main thing what i missed here is Authorizing my service account client ID with the GSUITE admin.
And I have been trying to generate access_token for the expired domain of mine.
After clearing all these i have to success in generating and getting user data.
This solution worked for me. I hope it works for you tooo....
Thank you community.

Box - How to create a Service Account

I'd like to create a Service Account so I'd be able to authenticate with it with my app.
All I found is this guide, but it doesn't say how to create such an account.
Can anyone assist?
Thanks
The docs aren't that clear but a Service Account == App. So if you create an app in the developer console and set authentication type to server authentication (jwt) and add your public key and get the app authorized in the admin console then you're ready to instantiate a service account with the following code:
String privateKey = new String(Files.readAllBytes(Paths.get(PRIVATE_KEY_FILE)));
JWTEncryptionPreferences encryptionPref = new JWTEncryptionPreferences();
encryptionPref.setPublicKeyID(PUBLIC_KEY_ID);
encryptionPref.setPrivateKey(privateKey);
encryptionPref.setPrivateKeyPassword(PRIVATE_KEY_PASSWORD);
encryptionPref.setEncryptionAlgorithm(EncryptionAlgorithm.RSA_SHA_256);
IAccessTokenCache accessTokenCache = new InMemoryLRUAccessTokenCache(MAX_CACHE_ENTRIES);
// BoxDeveloperAPIConnection == Service Account
BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(ENTERPRISE_ID, CLIENT_ID, CLIENT_SECRET, encryptionPref, accessTokenCache);

TFS REST API: How to "Make requests on behalf of others"?

I want my VSTS extension (installed on-prem TFS2015.3) to be able to do specific requests on behalf of a admin/service account ("Make requests on behalf of others")
Background: I manipulate (WorkItem) Process Template, specifically the GLOBALWORKFLOW (only on team-project level) in my extensions typescript, but the user of the extension in Web Access is NOT a project-admin so he is not allowed to use the function updateWorkItemTypeDefinition() - Non-Project-Admins get "Access denied" even if I gave that custom group every permission available ("Edit project-level-information" permissions for project-level GLOBALWORKFLOWs? Still didn't work for custom groups, only for Project Admin Accounts).
It seems I'm forced to impersonate a project admin /service account which is allowed to change the global workflow in the project
How do I impersonate in extension typescript code on-prem TFS and REST (1. not .NET and 2. without changing to basic auth, saw that solution already somewhere else - but I'm very sure I cannot request that change in my organization)
Thanks for your help
You can impersonate user through vsts-node-api.
There are many function to impersonate user, such as Basic, NTLM, PWA (VSTS) etc..., you can check these function here.
import * as vm from 'vso-node-api';
// your collection url
var collectionUrl = "XXX";
let authHandler = vm.getNtlmHandler("[user name]","[password]","[workstation optional]","[domain optional]");
var connect = new vm.WebApi(collectionUrl, authHandler);
There is the sample that you could refer to.