如何在 .net 中使用 ServiceAccount 使用 Google OAuth2? [英] how use Google OAuth2 using ServiceAccount in .net?

查看:27
本文介绍了如何在 .net 中使用 ServiceAccount 使用 Google OAuth2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何示例如何使用 .net 中的服务帐户访问谷歌服务 API?

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	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?

推荐答案

  1. 创建服务帐户密钥凭据
  2. 为服务创建私钥.(关键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": "...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"
    }

  1. 使用此 json,您必须生成一个 c# 类.您可以使用 (http://json2csharp.com/).这样更快
  2. 使用此代码生成凭证:

       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));

这篇关于如何在 .net 中使用 ServiceAccount 使用 Google OAuth2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆