首页 > 解决方案 > 使用 .NET Core 进行 Google API 客户端库身份验证

问题描述

我们正在使用.NET Core 3.1开发一个Web应用程序。我们想使用Google.Apis.Drive.v3 NuGet 包列出保存在 Google Drive 中的所有文件。我们要从中检索文件的帐户将始终相同,例如。company-data@company.com. 我们找到了有关如何在 Web 应用程序中进行身份验证的官方文档。但是,此示例似乎不适用于 .NET Core。

任何人都可以提供一个简单的示例来说明如何针对 Google Drive API 进行身份验证并列出所有文件。官方文档根本不涵盖 .NET Core。

编辑:这里有一个非常相似的问题。不幸的是,没有答案。

标签: c#asp.net-coregoogle-apigoogle-api-dotnet-client

解决方案


这是一个谷歌分析的例子,如果你需要帮助来改变它,请告诉我。

启动.cs

public class Client
    {
        public class Web
        {
            public string client_id { get; set; }
            public string client_secret { get; set; }
        }

        public Web web { get; set; }
    }



    public class ClientInfo
    {
        public Client Client { get; set;  }

        private readonly IConfiguration _configuration;

        public ClientInfo(IConfiguration configuration)
        {
            _configuration = configuration;
            Client = Load();
        }

        private Client Load()
        {
            var filePath = _configuration["TEST_WEB_CLIENT_SECRET_FILENAME"];
            if (string.IsNullOrEmpty(filePath))
            {
                throw new InvalidOperationException(
                    $"Please set the TEST_WEB_CLIENT_SECRET_FILENAME environment variable before running tests.");
            }

            if (!File.Exists(filePath))
            {
                throw new InvalidOperationException(
                    $"Please set the TEST_WEB_CLIENT_SECRET_FILENAME environment variable before running tests.");
            }

            var x = File.ReadAllText(filePath);

            return JsonConvert.DeserializeObject<Client>(File.ReadAllText(filePath));
        }
    }

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<ClientInfo>();

            services.AddControllers();

            services.AddAuthentication(o =>
                {
                    // This is for challenges to go directly to the Google OpenID Handler, so there's no
                    // need to add an AccountController that emits challenges for Login.
                    o.DefaultChallengeScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
                    // This is for forbids to go directly to the Google OpenID Handler, which checks if
                    // extra scopes are required and does automatic incremental auth.
                    o.DefaultForbidScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
                    o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                })
                .AddCookie()
                .AddGoogleOpenIdConnect(options =>
                {
                    var clientInfo = new ClientInfo(Configuration);
                    options.ClientId = clientInfo.Client.web.client_id;
                    options.ClientSecret = clientInfo.Client.web.client_secret;
                });
            services.AddMvc();
        }


        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();
            
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }
    }

具有身份验证的控制器

[ApiController]
[Route("[controller]")]
public class GAAnalyticsController : ControllerBase
{
    
    private readonly ILogger<WeatherForecastController> _logger;

    public GAAnalyticsController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    // Test showing use of incremental auth.
    // This attribute states that the listed scope(s) must be authorized in the handler.
    [GoogleScopedAuthorize(AnalyticsReportingService.ScopeConstants.AnalyticsReadonly)]
    public async Task<GetReportsResponse> Get([FromServices] IGoogleAuthProvider auth, [FromServices] ClientInfo clientInfo)
    {
        var GoogleAnalyticsViewId = "78110423";

        var cred = await auth.GetCredentialAsync();
        var service = new  AnalyticsReportingService(new BaseClientService.Initializer
        {
            HttpClientInitializer = cred
        });
        
        var dateRange = new DateRange
        {
            StartDate = "2015-06-15",
            EndDate = "2015-06-30"
        };

        // Create the Metrics object.
        var sessions = new Metric
        {
            Expression = "ga:sessions",
            Alias = "Sessions"
        };

        //Create the Dimensions object.
        var browser = new Dimension
        {
            Name = "ga:browser"
        };

        // Create the ReportRequest object.
        var reportRequest = new ReportRequest
        {
            ViewId = GoogleAnalyticsViewId,
            DateRanges = new List<DateRange> {dateRange},
            Dimensions = new List<Dimension> {browser},
            Metrics = new List<Metric> {sessions}
        };

        var requests = new List<ReportRequest> {reportRequest};

        // Create the GetReportsRequest object.
        var getReport = new GetReportsRequest {ReportRequests = requests};

        // Make the request.
        var response = service.Reports.BatchGet(getReport).Execute();
        return response;
    }
}

推荐阅读