如何在 .net 中使用 ServiceAccount 使用 Google OAuth2?

编程入门 行业动态 更新时间:2024-10-25 00:33:57
本文介绍了如何在 中使用 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:关键词]

本文发布于:2023-03-28 00:25:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/712545.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   net   ServiceAccount   Google

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!