Is there any sample how to access a google service API using service account in .net?
private const string SERVICE_ACCOUNT_EMAIL = "xxxxxxxxxxx#developer.gserviceaccount.com";
private const string SERVICE_ACCOUNT_PKCS12_FILE_PATH = #"\path\test-privatekey.p12";
static DriveService BuildService()
{
X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret",
X509KeyStorageFlags.Exportable);
var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
{
ServiceAccountId = SERVICE_ACCOUNT_EMAIL,
Scope = DriveService.Scopes.Drive.GetStringValue(),
};
var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);
return new DriveService((new BaseClientService.Initializer()
{
Authenticator = auth
});
}
This isn't successful in returning a OAuth connection. How can this be done?
Create a Service Account Keys credencial
Create private key for service. (Key json).
Example:
{
"type": "service_account",
"project_id": "...",
"private_key_id": "....",
"private_key": "....",
"client_email": ".....#developer.gserviceaccount.com",
"client_id": "....",
"auth_uri": "...accounts.google.com/o/oauth2/auth",
"token_uri": "...accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "...www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "...www.googleapis.com/robot/v1/metadata/x509/....-compute%40developer.gserviceaccount.com"
}
With this json you must generate a c# class. You can using (http://json2csharp.com/). This is faster
Use this code to generate credencial:
var _pathJson = #"C:\servicekey.json";
var json = File.ReadAllText(_pathJson);
var cr = JsonConvert.DeserializeObject<PersonalServiceAccountCred>(json);
// "personal" service account credential
// Create an explicit ServiceAccountCredential credential
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cr.ClientEmail)
{
Scopes = new[] { YouTubeService.Scope.YoutubeUpload /*Here put scope that you want use*/}
}.FromPrivateKey(cr.PrivateKey));
This case work in my site
var certificate = new X509Certificate2("pathTo***.p12", "notasecret", X509KeyStorageFlags.Exportable);
var serviceAccountEmail = "********-*********#developer.gserviceaccount.com";
var userAccountEmail = "******#gmail.com";
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { DriveService.Scope.Drive },
User = userAccountEmail
}.FromCertificate(certificate));
// Create the service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "*****",
});
Related
How to stop my livestream in YouTube while completed my live telecast using c#
How to stop the livestream Using c# Code, can you please give some suggestion
string[] scopes = { "https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.upload" };
var creadentails = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = YTPublishSettings.PublisherClientId,
ClientSecret = YTPublishSettings.PublisherClientSecret,
},
scopes, "user", default).Result;
if (creadentails.Token.IsExpired(SystemClock.Default))
creadentails.RefreshTokenAsync(CancellationToken.None).Wait();
var secrets = new ClientSecrets
{
ClientId = YTPublishSettings.PublisherClientId,
ClientSecret = YTPublishSettings.PublisherClientSecret,
};
var token = new TokenResponse { RefreshToken = creadentails.Token.RefreshToken };
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets }),
"user", token);
var service = new YouTubeService(new BaseClientService.Initializer
{
HttpClientInitializer = credentials,
ApplicationName = "**************",
});
var broadcast = new LiveStream
{
Cdn = new CdnSettings
{
FrameRate = "35fps",
IngestionType = "rtmp",
Resolution = "720p"
},
Snippet = new LiveStreamSnippet
{
Description = Description,
Title = Title,
},
};
var request = service.LiveStreams.Delete(YTPublishSettings.PublisherId);
var response = request.Execute();
return new YouTubeStreamDeleteStatus()
{
success = "Deleted",
};
How can end My YouTube live stream API in c#?
I have problem while connecting to Amazon SP API. I have follow the guideline on Amazon https://github.com/amzn/selling-partner-api-docs/blob/main/guides/en-US/developer-guide/SellingPartnerApiDeveloperGuide.md
The C# SDK that I used is https://github.com/amzn/selling-partner-api-models
I have add below inline policy to my IAM user
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": "arn:aws:iam::0000000:role/SellingPartnerAPI_Role"
}
]
}
Below is my c# source code
var accessKey = "xxx";
var secretKey = "xxx";
var credentials = new BasicAWSCredentials(accessKey, secretKey);
var client = new AmazonSecurityTokenServiceClient(credentials);
var assumeRoleRequest = new AssumeRoleRequest()
{
// AWS IAM Role ARN
DurationSeconds = 3600,
RoleArn = "arn:aws:iam::0000000000:role/SellingPartnerAPI_Role",
RoleSessionName = DateTime.Now.Ticks.ToString()
};
AssumeRoleResponse assumeRoleResponse = await client.AssumeRoleAsync(assumeRoleRequest);
RestClient restClient = new RestClient("https://sellingpartnerapi-fe.amazon.com");
IRestRequest restRequest = new RestRequest("/orders/v0/orders", Method.GET);
restRequest.AddQueryParameter("CreatedAfter", "2020-12-01T00:00:00Z");
restRequest.AddQueryParameter("marketplaceIds", "A21BRDQVFO45XV");
var lwaAuthCreds = new LWAAuthorizationCredentials
{
ClientId = "amzn1.application-oa2-client.xxxxxxxxxx",
ClientSecret = "ClientSecretxxxxx",
RefreshToken = "RefreshTokenxxxxxx,
Endpoint = new Uri("https://api.amazon.com/auth/o2/token")
};
restRequest = new LWAAuthorizationSigner(lwaAuthCreds).Sign(restRequest);
var awsAuthCreds = new AWSAuthenticationCredentials
{
AccessKeyId = assumeRoleResponse.Credentials.AccessKeyId,
SecretKey = assumeRoleResponse.Credentials.SecretAccessKey,
Region = "us-west-2"
};
restRequest.AddHeader("X-Amz-Security-Token", assumeRoleResponse.Credentials.SessionToken);
restRequest = new AWSSigV4Signer(awsAuthCreds)
.Sign(restRequest, restClient.BaseUrl.Host);
var resp = restClient.Execute(restRequest);
Console.WriteLine(resp.StatusCode);
Console.WriteLine(resp.Content);
The response is
{
"errors": [
{
"message": "The security token included in the request is invalid",
"code": "InvalidInput"
}
]
}
I have a project in Google Apps for which I've enabled Calendar API and Gmail API (generated a '.p12' key for server-to-server authentication). I've managed to read/write my Google Calendar account with the following:
private CalendarService GetCalendarService()
{
var certificate = new X509Certificate2(_googleCredentialsFilePath, "notasecret", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
var serviceEmail = "599172797645-dthli52ji7j0j53gacmqigvs694bu7vs#developer.gserviceaccount.com";
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceEmail)
{
Scopes = new[] { CalendarService.Scope.Calendar, CalendarService.Scope.CalendarReadonly }
}.FromCertificate(certificate));
var applicationName = ConfigurationManager.AppSettings["ApplicationName"];
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = applicationName,
});
return service;
}
With the service object I can create events in my calendars like so:
var newEvent = new Event()
{
Summary = calendarEvent.Summary,
Description = calendarEvent.Description,
Start = new EventDateTime()
{
DateTime = calendarEvent.StartDateTime,
TimeZone = _ianaTimezone,
},
End = new EventDateTime()
{
DateTime = calendarEvent.EndDateTime,
TimeZone = _ianaTimezone,
}
};
var request = _calendarService.Events.Insert(newEvent, googleCalendarId);
var result = request.Execute(); // CREATE EVENT SUCCESSFULLY
Now, for the Gmail API client I'd like to send emails using the service account owner email (the same I use to login Google Dev Console -- "mypersonalemail#gmail.com"
private GmailService GetGmailService()
{
var certificate = new X509Certificate2(_googleCredentialsFilePath, "notasecret", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
var serviceEmail = "599172797645-dthli52ji7j0j53gacmqigvs694bu7vs#developer.gserviceaccount.com";
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceEmail)
{
Scopes = new[] { GmailService.Scope.MailGoogleCom, GmailService.Scope.GmailCompose, GmailService.Scope.GmailModify, GmailService.Scope.GmailSend },
User = "mypersonalemail#gmail.com"
}.FromCertificate(certificate));
var applicationName = ConfigurationManager.AppSettings["ApplicationName"];
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = applicationName,
});
return service;
}
But when I try to test this client requesting the list of drafts:
ListDraftsResponse draftsResponse = _gmailService.Users.Drafts.List("mypersonalemail#gmail.com").Execute();
Then I get the error:
"Error:\"unauthorized_client\", Description:\"Unauthorized client or scope in request.\", Uri:\"\"" string
I've logged in to Google Developers Console with mypersonalemail#gmail.com and in
API Manager > Permissions > Add service account owner added "mypersonalemail#gmail.com" as the service email owner (probably redundantly)
Do I need a Google Apps for Work to send/read emails from my own gmail account via service account? My app is currently hosted in Azure as a web application.
Check This
And make sure that you access the google.Admin account for referencing the service account Client ID of the app you created and the time zone is in the following format "America/Phoenix".
I am building a YouTube app for windows 8.1.
I am having a trouble with, add(Insert) subscription is fail
my code:
var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new Uri("ms-appx:///Assets/client_secrets.json"),
new[] { Uri.EscapeUriString(YouTubeService.Scope.Youtube) },
"user",
CancellationToken.None);
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
HttpClientInitializer = credential,
ApplicationName = "AppName"
});
Subscription body = new Subscription();
body.Snippet = new SubscriptionSnippet();
body.Snippet.ChannelId = "UC-kezFAw46x-9ctBUqVe86Q";
try
{
var addSubscriptionRequest = youtubeService.Subscriptions.Insert(body, "snippet");
var addSubscriptionResponse = await addSubscriptionRequest.ExecuteAsync();
}
catch (Exception e)
{
throw e;
}
When I set a breakpoint at the first line.
when execute to last line, breaks this function
Update(2015-11-14):
Error Message:
The subscription resource specified in the request must use the snippet.resorceId property to identify the channel that is being subscribed to [400]
Successful Code:
var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new Uri("ms-appx:///Assets/client_secrets.json"),
new[] { Uri.EscapeUriString(YouTubeService.Scope.Youtube) },
"user",
CancellationToken.None);
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
//ApiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
HttpClientInitializer = credential,
ApplicationName = "4GameTV"
});
try
{
Subscription body = new Subscription();
body.Snippet = new SubscriptionSnippet();
body.Snippet.ResourceId = new ResourceId();
body.Snippet.ResourceId.ChannelId = "UC-kezFAw46x-9ctBUqVe86Q"; //replace with specified channel id
var addSubscriptionRequest = youtubeService.Subscriptions.Insert(body, "snippet");
var addSubscriptionResponse = await addSubscriptionRequest.ExecuteAsync();
}
catch (Exception e)
{
throw e;
}
Your authentication seems a bit off from what I normally use. Also ApiKey is only needed if you want to access public data.
string[] scopes = new string[] { YouTubeService.Scope.Youtube };
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
, scopes
, "test"
, CancellationToken.None
, new FileDataStore("Daimto.YouTube.Auth.Store")).Result;
YouTubeService service = new YouTubeService(new YouTubeService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "YouTube Data API Sample",
});
I'm trying to upload a CSV file using google analytics api and it gives me a status failed.
The error that I'm getting is variable is null: parameter name base uri
I have given the permissions for google analytics api in developer console and I'm using service account to generate the key and the id's.
This is my code snippet
const string serviceAccountEmail = "716698526626-6s61a3tbe1m5mofo9#developer.gserviceaccount.com";
const string serviceAccountPKCSP12FilePath = #"C:\SVN\GAPforInboundandWeb-1f6bfb.p12";
X509Certificate2 certificate = new X509Certificate2(serviceAccountPKCSP12FilePath, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { AnalyticsService.Scope.Analytics }
}.FromCertificate(certificate));
var service = new AnalyticsService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "GAPforInboundandWeb"
});
FileStream realCsv = new FileStream("c:\\real.csv", FileMode.Open);
// Create the service.
try
{
var upload = service.Management.DailyUploads.Upload("50288725", "UA-50288725-1", "Oy_0JTPvRGCB3Vg5OKVIMQ",
"2014-09-22", 1, ManagementResource.DailyUploadsResource.UploadMediaUpload.TypeEnum.Cost, realCsv,
"application/octet-stream");
upload.Reset = true;
var res = upload.Upload();
res.BytesSent.ToString();
res.Status.ToString();
}
I resolved the same problem. In my case, its a wrong DataSourceId.
Try this:
const string serviceAccountEmail = "716698526626-6s61a3tbe1m5mofo9#developer.gserviceaccount.com";
const string serviceAccountPKCSP12FilePath = #"C:\SVN\GAPforInboundandWeb-1f6bfb.p12";
X509Certificate2 certificate = new X509Certificate2(serviceAccountPKCSP12FilePath, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { AnalyticsService.Scope.Analytics }
}.FromCertificate(certificate));
var service = new AnalyticsService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "GAPforInboundandWeb"
});
FileStream realCsv = new FileStream("c:\\real.csv", FileMode.Open);
// Create the service.
try
{
var dataSource = srv.Management.CustomDataSources.List(AccountId, WebId).Execute();
var strDataSourceId = "Oy_0JTPvRGCB3Vg5OKVIMQ";
if(dataSource!=null && dataSource.Items.Length>0)
strDataSourceId =dataSource.Items[0].Id;
var upload = service.Management.DailyUploads.Upload("50288725", "UA-50288725-1", strDataSourceId,
"2014-09-22", 1, ManagementResource.DailyUploadsResource.UploadMediaUpload.TypeEnum.Cost, realCsv,
"application/octet-stream");
upload.Reset = true;
var res = upload.Upload();
res.BytesSent.ToString();
res.Status.ToString();
}
Use List methods on service.Management.CustomDataSources and service.Management.Uploads in this order for check your config.