Get access_token from google service account for embed api - google-api

I've wanted to embed api without my user logging in to their account. I'm new to google api and I wanted to use embed api Like this one
I've been searching since yesterday how to implement this either by javascript or .net.
I have this code in .net
string keyFilePath = Server.MapPath("~/Libraries/googleKey/key.json");
string json = System.IO.File.ReadAllText(keyFilePath);
var cr = JsonConvert.DeserializeObject<PersonalServiceAccountCred>(json);
var xCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cr.client_email)
{
Scopes = new[] {
AnalyticsReportingService.Scope.AnalyticsReadonly
}
}.FromPrivateKey(cr.private_key));
I'm getting a null token, i'm confused, most examples are in php or python.

you can use a service Account, make sure you have access granted to the service account

Related

Google Admin Setttings API connection for .NET

I've been working with the Google directory API for quite some time now.
However, I need to update SSO settings in the admin settings section of Google. Yes, they say it will be deprecated at some point, but according to a google employee, it's going to be a while before a new API is available and then the old one will be removed.
First, if there is a NUGET package out there, please let me know. I can't seem to find anything that works with the admin settings API: https://developers.google.com/admin-sdk/admin-settings/
My first attempt is getting the SSO settings in Google.
I can use postman to pull this information so I know the API works.
However, I'm running into two issues:
How can I authenticate using the service certificate that I use in the apis.google.directory class?
Anticipating, how do I request access to the admin settings? In directory API, I have the scope enum to select from. If I'm making a manual connection to the API I assume I'll need to call this by hand?
Code
var certificate = new X509Certificate2(serviceAccountCertPath,
serviceAccountCertPassword,
X509KeyStorageFlags.Exportable);
// below the scopes are going to get in my way, right? What is the scope process I need to do for this manually?
credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { DirectoryService.Scope.AdminDirectoryUser,
DirectoryService.Scope.AdminDirectoryGroup,
DirectoryService.Scope.AdminDirectoryOrgunit},
User = _szAdminEmail
}.FromCertificate(certificate));
// I'm not seeing anyway to call the above credentials
using (HttpClient client = new HttpClient())
{
// client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
client.BaseAddress = new Uri(#"https://apps-apis.google.com/a/feeds/domain/2.0/[mydomain]/sso/general");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//client.DefaultRequestHeaders.
HttpResponseMessage response = client.GetAsync("api/Values").Result; // Blocking call!
var products = response.Content.ReadAsStringAsync().Result;
return products.ToString();
}
The admin settings API does not appear to support service account authentication you will need to use Oauth2. Admin Settings Oauth
Your not going to be able to use it very easily using the Google .net client library as that library was designed for use with the Google discovery apis. I dont think the Admin Settings API is a discovery api. You might be able to use the old gdata library for it I am not sure if one exists I have not been able to find it on nuget. If you do find it the old gdata library doesn't support oauth2 which means that you will need to use the new library for that and plug in the gdata library after.
I have only done this before using the Google contacts api I have a tutorial here on how i did it it may help you here
Auth
string clientId = "xxxxxx.apps.googleusercontent.com";
string clientSecret = "xxxxx";
string[] scopes = new string[] { "https://www.googleapis.com/auth/contacts.readonly" }; // view your basic profile info.
try
{
// Use the current Google .net client library to get the Oauth2 stuff.
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
, scopes
, "test"
, CancellationToken.None
, new FileDataStore("test")).Result;
// Translate the Oauth permissions to something the old client libray can read
OAuth2Parameters parameters = new OAuth2Parameters();
parameters.AccessToken = credential.Token.AccessToken;
parameters.RefreshToken = credential.Token.RefreshToken;
RunContactsSample(parameters);
If you cant find the gdata library for it you may have better luck just using the library for authencation and then code the rest of the calls yourself. It returns xml not json.

Google Drive API's file Export endpoint is failing with API Key authentication?

Has anything changed recently with the Google Drive APIs and specifically the Export function, which would cause it to fail while using API Key access after 27-Mar-2018?
I have a Windows Service that creates and sends daily course emails for an educational group. The source content for each email is stored in a Google Drive, as a Google Doc, so that the faculty can update the course content easily.
This has been working flawlessly for the past year, but suddenly stopped working about 27-Mar-2018. Since then, I can retrieve the file details;
_googleDriveHtmlContent.LoadFile(
fileId
);
But not the contents. When I Export the file as HTML, I immediately get a DownloadStatus.Failed from the ProgressChanged handler;
var request = _driveService.Files.Export(
fileId,
"text/html"
);
I'm using API keys for security, rather than OAuth, since it's a UI-less service. To do this I need to mark the file folders as publicly accessible - specifically I'm using "Accessible to everyone, with link." This has been working great.
I've updated to the latest API v3 libraries through NuGet, with no change in behavior.
Using Google's API Explorer, I'm seeing a similar behavior.
I can retrieve my file successfully using the API Explorer with the get endpoint.
https://developers.google.com/drive/v3/reference/files/get
fileId 1AIuGhzXsNuhhi0PMA1pblh0l5CCDaa1nPj8t_dasi_c
Authentication: API key (uses a "demo API key")
But with the export endpoint, I get an Internal Error (500)-
https://developers.google.com/drive/v3/reference/files/export
fileId 1AIuGhzXsNuhhi0PMA1pblh0l5CCDaa1nPj8t_dasi_c
mimeType: text/html
Authentication: API key (uses a "demo API key")
Changing the Authentication in the API Explorer to OAuth 2.0, and approving access, then returns a successful 200 result with the file HTML. However I'm unable to do that since I'm accessing the API via a UI-less service.
Has anything changed recently with the Google Drive APIs and specifically the Export function, which would cause it to fail while using API Key access after 27-Mar-2018?
Its possible but its most likely a stealth change that you will not get any official word on. Not that long ago i saw someone posting a similar question they were using an API key to update a Google sheet and it suddenly stopped working.
IMO if google has changed this its probably a good thing. API keys are meant for accessing public data. Setting a document to public is a really bad idea if anyone did manage to find the file ID of your document they would then be able to update your document.
Suggestion:
What you should be using is a Service account. Service accounts are dummy users by creating service account credentials on Google developer console and then taking the service account email address you can share the file on Google Drive with the service account granting it access to said file without the need of making the file public.
You havent specified what language you are using but you said you were making a windows service so i am going to assume you are using .net. Here is an example of service account authencation with the Google .net client library.
public static DriveService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath, string[] scopes)
{
try
{
if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
throw new Exception("Path to the service account credentials file is required.");
if (!File.Exists(serviceAccountCredentialFilePath))
throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath);
if (string.IsNullOrEmpty(serviceAccountEmail))
throw new Exception("ServiceAccountEmail is required.");
// For Json file
if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
{
GoogleCredential credential;
using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(scopes);
}
// Create the Analytics service.
return new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive Service account Authentication Sample",
});
}
else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
{ // If its a P12 file
var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = scopes
}.FromCertificate(certificate));
// Create the Drive service.
return new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive Authentication Sample",
});
}
else
{
throw new Exception("Unsupported Service accounts credentials.");
}
}
catch (Exception ex)
{
throw new Exception("CreateServiceAccountDriveFailed", ex);
}
}
}
code ripped from serviceaccount.cs. Assuming that you were already using the Google .net client library the service this method returns will be the same drive service you were using with an api key.
Once you have granted your service account access to the file it will be able to access the file when ever it needs there is no authentication needed as you have preauthorized it by sharing the file with it.

How to access Google API in combination with Azure AD single-sign on

I have a web application running on Azure. The web application authenticates the users via OpenID Connect from a Azure Active Directory tenant.
Azure Sample on GitHub.
On the Azure Active Directory tenant I have integrated Google Apps and configured single sing-on to Google Apps and automated user provisioning. Tutorial: How to integrate Google Apps with Azure Active Directory.
In my web application I would like to access user content from Google Apps (e.g. files on Google Drive) of the signed in user via Google API.
Is it possible to do this with the help of the setup single sign-on federation, so that the user only needs to sign in to the web application/Azure AD and for the Web API call there is no need for a further sign in, e.g. by using a token optained by Azure AD for accessing the Google Web API?
Tokens obtained from Azure AD cannot be used directly against Google API. However if you integrated Azure AD and Google Apps you should be able to go through the google token acquisition process without gathering user credentials again. You might want to go through an authorization code flow for getting tokens from google, and inject in the request information that would help to leverage your existing session. Typical examples are passing your user's UPN (via login_hint query parameter) and tenant (domain_hint). However I don't know if the google authorization endpoint will pass those along, you'll need to consult the google api documentation.
I ended up with two solutions:
a) Service Account:
Accessing the users data with a service account on behalf of a user.
For this you have to setup a service account: Using OAuth 2.0 for Server to Server Applications
private static ServiceAccountCredential GetServiceAccountCredential(string user)
{
const string privateKey = "<PRIVATEKEY>";
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer("<SERVICEACOUNTEMAIL>")
{
Scopes = new[] {DriveService.Scope.Drive},
User = user
}.FromPrivateKey(privateKey));
return credential;
}
b) User:
Accessing the users data with the user. For this you have to register your app to get the client ID and secret: Using OAuth 2.0 for Web Server Applications
private static UserCredential GetUserCredential(string user)
{
ClientSecrets secrets = new ClientSecrets
{
ClientId = "<CLIENTID>",
ClientSecret = "<CLIENTSECRET>"
};
IDataStore credentialPersistanceStore = new FileDataStore("Drive.Sample.Credentials");
Task<UserCredential> result = GoogleWebAuthorizationBroker.AuthorizeAsync(
secrets,
new[] {DriveService.Scope.Drive},
user,
CancellationToken.None,
credentialPersistanceStore);
result.Wait();
UserCredential credential = result.Result;
return credential;
}
With the credentials I can request the files from Drive:
Claim emailClaim = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email);
IConfigurableHttpClientInitializer credential = GetServiceAccountCredential(emailClaim.Value);
//IConfigurableHttpClientInitializer credential = GetUserCredential(emailClaim.Value);
var service = new DriveService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "My App"
});
FileList list = service.Files.List().Execute();
I am not yet sure which option I will use. Maybe you have some advices or suggestions.

Google Domain Shared Contacts API Using OAuth 2.0 for Server to Server Applications - Credential params

I'm trying to get the "Google Domain Shared Contacts API" described here:
https://developers.google.com/admin-sdk/domain-shared-contacts/
Working using "OAuth 2.0 for Server to Server Applications" described here:
https://developers.google.com/accounts/docs/OAuth2ServiceAccount
The recommendation from the OAuth page is to use the provided Google client library... I'm using the Java library. But the Shared-Contacts API doesn't have an example that uses this library, and I'm having trouble figuring out how to use the library with the Shared-Contacts API.
I am able to make the example for the OAuth to work for me... It uses Google Cloud Storage. Here's a snippet of the code:
String STORAGE_SCOPE = "https://www.googleapis.com/auth/devstorage.read_write";
try {
try {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
String p12Content = Files.readFirstLine(new File(keyFile), Charset.defaultCharset());
// Build service account credential.
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Collections.singleton(STORAGE_SCOPE))
.setServiceAccountPrivateKeyFromP12File(new File(keyFile))
.build();
// Set up and execute Google Cloud Storage request.
String URI;
URI = "https://storage.googleapis.com/" + BUCKET_NAME;
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
GenericUrl url = new GenericUrl(URI);
HttpRequest request = requestFactory.buildGetRequest(url);
HttpResponse response = request.execute();
content = response.parseAsString();
} catch (IOException e) {
System.err.println(e.getMessage());
}
} catch (Throwable t) {
t.printStackTrace();
}
return content;
It's a request to get a listing of what's in a certain bucket on GCS. It calls a specific URL using the Credentials object, where the Credentials object does the work of the OAuth, using a key file I downloaded. There's other steps involved for getting it to work (setting the service account email, etc), which I did. It returns an xml string containing what is inside the bucket, and it works fine for me.
I then tried changing the URI to this string:
URI = "https://www.google.com/m8/feeds/contacts/myGoogleAppsDomain.com/full";
and I changed the STORAGE_SCOPE variable to be this string:
STORAGE_SCOPE = "http://www.google.com/m8/feeds/";
Hoping it would then return an xml-string of the shared-contacts. But instead, it returns this error:
403 Cannot request contacts belonging to another domain
I believe I'm getting this error because I'm not specifying the "hd" parameter when I do the authentication request... However, I'm unsure how I can specify the "hd" parameter using the GoogleCredential object (or the other parameters, except for "scope")... Can someone help me with that?
I think the issue here is that you are not specifying which user you want to impersonate in the domain (and you haven't configured the security settings in your domain to authorize the service account to impersonate users in the domain).
The doubleclick API auth documentation has good examples on how to do this. You can use their sample and replace the scopes and API endpoint:
https://developers.google.com/doubleclick-publishers/docs/service_accounts#benefits

Google Group Settings API enabled for service accounts?

Most of the Google Management APIs seem to have been enabled for Service Accounts. For example, I can retrieve calendars like so:
string scope = Google.Apis.Calendar.v3.CalendarService.Scopes.Calendar.ToString().ToLower();
string scope_url = "https://www.googleapis.com/auth/" + scope;
string client_id = "999...#developer.gserviceaccount.com";
string key_file = #"\path\to\my-privatekey.p12";
string key_pass = "notasecret";
AuthorizationServerDescription desc = GoogleAuthenticationServer.Description;
X509Certificate2 key = new X509Certificate2(key_file, key_pass, X509KeyStorageFlags.Exportable);
AssertionFlowClient client = new AssertionFlowClient(desc, key) { ServiceAccountId = client_id, Scope = scope_url };
OAuth2Authenticator<AssertionFlowClient> auth = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);
CalendarService service = new CalendarService(auth);
var x = service.Calendars.Get("calendarID#mydomain.com").Fetch();
However, identical code on the GroupssettingsService returns a 503 - Server Not Available. Does that mean service accounts can't be used with that API?
In a possibly related issue, the scope of the Groups Settings Service seems to be apps.groups.settings but if you call
GroupssettingsService.Scopes.AppsGroupsSettings.ToString().ToLower();
...you get appsgroupssettings instead, without the embedded periods.
Is there another method to use service accounts for the GroupssettingsService? Or any information on the correct scope string?
Many thanks.
I found this thread, and the most important part of the docs after some time. Posting so others don't waste their time in the future.
Your application must use OAuth 2.0 to authorize requests. No other authorization protocols are supported. If your application uses Google Sign-In, some aspects of authorization are handled for you.
See the "About authorization protocols" section of the docs
Why do you need to use a service account for this? You can use regular OAuth 2.0 authorization flows to get an authorization token from a Google Apps super admin user and use that:
https://developers.google.com/accounts/docs/OAuth2InstalledApp

Resources