Is there any sample how to access a google service API using service account in .net?
private const string SERVICE_ACCOUNT_EMAIL = "[email protected]";
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?
Visit the Google API Console to obtain OAuth 2.0 credentials such as a client ID and client secret known to both Google and your application. 2. Obtain an access token from the Google Authorization Server.
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 = "*****",
});
{
"type": "service_account",
"project_id": "...",
"private_key_id": "....",
"private_key": "....",
"client_email": "[email protected]",
"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"
}
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With