本文介绍了如何在 中使用 ServiceAccount 使用 Google OAuth2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有任何示例如何使用 中的服务帐户访问谷歌服务 API?
Is there any sample how to access a google service API using service account in ?
private const string SERVICE_ACCOUNT_EMAIL = "xxxxxxxxxxx@developer.gserviceaccount";
private const string SERVICE_ACCOUNT_PKCS12_FILE_PATH = @"path est-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
});
}
这无法成功返回 OAuth 连接.这怎么办?
This isn't successful in returning a OAuth connection. How can this be done?
推荐答案
创建服务帐户密钥凭据为服务创建私钥.(关键json).示例: {
"type": "service_account",
"project_id": "...",
"private_key_id": "....",
"private_key": "....",
"client_email": ".....@developer.gserviceaccount",
"client_id": "....",
"auth_uri": "...accounts.google/o/oauth2/auth",
"token_uri": "...accounts.google/o/oauth2/token",
"auth_provider_x509_cert_url": "...www.googleapis/oauth2/v1/certs",
"client_x509_cert_url": "...www.googleapis/robot/v1/metadata/x509/....-compute%40developer.gserviceaccount"
}
使用此 json,您必须生成一个 c# 类.您可以使用 (http://json2csharp/).这样更快使用此代码生成凭证:
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));
这篇关于如何在 中使用 ServiceAccount 使用 Google OAuth2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论