为什么来自 .NET Core 3.1 的 Google Drive API 调用未经过身份验证?

问题描述 投票:0回答:1

我们有一个 .NET Core 3.1 项目,我们想在其中进行调用以从 Google Drive 获取 Google Drive 信息。

以此项目为基础

https://github.com/googleapis/google-api-dotnet-client/tree/master/Src/Support/Google.Apis.Auth.AspNetCore3.IntegrationTests

我们的项目实现了以下内容:

创建了一个项目并在我们的Google帐户中获取了client_id和secret。

包括 Google.Apis.Auth.AspNetCore3 和 Google.Apis.Drive.v3 包

  <ItemGroup>
    <PackageReference Include="Dapper" Version="2.0.78" />
    <PackageReference Include="Google.Apis.Auth.AspNetCore3" Version="1.49.0" />
    <PackageReference Include="Google.Apis.Drive.v3" Version="1.49.0.2194" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.11" />
    <PackageReference Include="Microsoft.Extensions.Options" Version="3.1.11" />
    <PackageReference Include="SendGrid" Version="9.22.0" />
    <PackageReference Include="StringTemplate4" Version="4.0.8" />
    <PackageReference Include="System.Data.SqlClient" Version="4.8.2" />
  </ItemGroup>

然后在 Startup.cs 中有以下内容可以与 Google Drive API 集成

public void ConfigureServices(IServiceCollection services)
{

 ...

  // This configures Google.Apis.Auth.AspNetCore3 for use in this app.
  services
      .AddAuthentication(o =>
      {
        // This forces challenge results to be handled by Google OpenID Handler, so there's no
        // need to add an AccountController that emits challenges for Login.
        o.DefaultChallengeScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
        // This forces forbid results to be handled by Google OpenID Handler, which checks if
        // extra scopes are required and does automatic incremental auth.
        o.DefaultForbidScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
        // Default scheme that will handle everything else.
        // Once a user is authenticated, the OAuth2 token info is stored in cookies.
        o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
      })
      .AddCookie()
      .AddGoogleOpenIdConnect(options =>
      {
        options.ClientId = "<client_id";
        options.ClientSecret = "<secret>";
      });

 ...

}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{

 ...

  // Google API initialization
  app.UseAuthentication();
  app.UseAuthorization();

 ...
}

然后控制器有以下方法来调用 Google Drive API

[GoogleScopedAuthorize(DriveService.ScopeConstants.DriveReadonly)]
public async Task<List<GDFolder>> GetRoot([FromServices] IGoogleAuthProvider auth)
{
  try
  {
    GoogleCredential cred = await auth.GetCredentialAsync();
    var service = new DriveService(new BaseClientService.Initializer
    {
      HttpClientInitializer = cred
    });
    var fileListRequest = service.Files.List();
    fileListRequest.Fields = "nextPageToken, files(id, name, mimeType, modifiedTime)";
    fileListRequest.PageSize = 25;
    fileListRequest.Q = $"'{ROOT_ID}' in parents and mimeType='{GDMIMETypeString.FOLDER}'{QUERY_EXCLUDETRASH}";

    var gdFiles = await fileListRequest.ExecuteAsync();


    return gdFiles;

  }
  catch (Exception exc)
  {
    throw new ApplicationException("Unable to get list of Google Drive files", exc);
  }

}

执行行 GoogleCredential cred = wait auth.GetCredentialAsync(); 时,会引发异常并出现以下错误。

“未经身份验证时无法获取凭证。”

我们的实现可能存在哪些错误导致此身份验证错误?

c# asp.net-core google-api google-drive-api google-api-dotnet-client
1个回答
0
投票

您可以通过这种方式轻松验证自己的身份 -->

{
    var yourClientEmail = "";
    var yourPrivateKey = "";

    var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(yourClientEmail)
    {
        Scopes = [DriveService.Scope.Drive]
    }.FromPrivateKey(yourPrivateKey));

    return new DriveService(new BaseClientService.Initializer
    {
        HttpClientInitializer = credential
    });
 }

您可以使用此返回来进行操作..

顺便说一句,您首先需要在谷歌云控制台中创建一个“服务帐户”,您可以在其中找到“clientEmail”和“privateKey”。

© www.soinside.com 2019 - 2024. All rights reserved.