如何在.net中使用Google OAuth2使用ServiceAccount?
是否有任何示例如何使用.net中的服务帐户访问Google服务API?
private const string SERVICE_ACCOUNT_EMAIL = "xxxxxxxxxxx@developer.gserviceaccount.com"; private const string SERVICE_ACCOUNT_PKCS12_FILE_PATH = @"pathtest-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(provider, AssertionFlowClient.GetState); return new DriveService((new BaseClientService.Initializer() { Authenticator = auth }); }
这在返回OAuth连接时不成功。 如何才能做到这一点?
这个案例在我的网站上工作
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 = "*****", });
- 创建服务帐户密钥credencial
-
为服务创建私钥。 (关键json)。 例:
{“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“:”…帐户.google.com / o / oauth2 / token“,”“auth_provider_x509_cert_url”:“… https://www.googleapis.com/oauth2/v1/certs”,“client_x509_cert_url”:“… https://www.googleapis.com/robot/v1 /metadata/x509/….-compute%40developer.gserviceaccount.com“}
-
有了这个json,你必须生成ac#class。 您可以使用( https://json2csharp.com/ )。 这更快
-
使用此代码生成credencial:
var _pathJson = @“C: servicekey.json”; var json = File.ReadAllText(_pathJson); var cr = JsonConvert.DeserializeObject(json); //“个人”服务帐户凭据//创建显式ServiceAccountCredential凭证var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cr.ClientEmail){Scopes = new [] {YouTubeService.Scope.YoutubeUpload / 这里放置您想要使用的范围 /}} .FromPrivateKey(cr.PrivateKey));
上述就是C#学习教程:如何在.net中使用Google OAuth2使用ServiceAccount?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1044156.html