【问题标题】:Google APIs Oauth .net core 3.1Google API Oauth .net 核心 3.1
【发布时间】:2020-10-08 17:36:01
【问题描述】:

我有一个 .net core 3.1 MVC Web 应用程序。我正在尝试开始使用一些 google api。我发现 Google 文档非常混乱。在官方文档中,我发现是一个不支持 .net 核心的 MVC 库。有人能指出我正确的方向吗 - 我应该如何开始在 MVC .net 核心 Web 应用程序上验证我的用户?我应该寻找非谷歌 oauth 库吗?谷歌是否支持我找不到的东西?

试图挖掘更多,我遇到了 Google.Apis.Auth.AspNetCore3。这是推荐的方法吗?关于如何使用它的任何文档,或者我应该自己下载源代码?我一头雾水。

【问题讨论】:

标签: .net-core google-api google-api-dotnet-client


【解决方案1】:

您可以在 .NET Core 3.1 中使用 Google.Apis.Auth.AspNetCore3 进行身份验证,它是 Google 维护和推荐的库。 Google.Apis.Auth.AspNetCore3.IntegrationTests 是一个很好的示例(它只是一个 ASP.NET Core 3 Web 应用程序),说明了如何使用该库并展示了它的所有功能。如果遇到任何问题,请随时在https://github.com/googleapis/google-api-dotnet-client 中提出问题。

【讨论】:

    【解决方案2】:

    这是一个谷歌分析的例子,如果你需要帮助改变它以适应不同的 api,请告诉我..

    startup.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;
        }
    }
    

    【讨论】:

    • 如果我们不使用 MVC 怎么办?我们能否获得一些文档,以便我们自己生成 OAuth 流程
    猜你喜欢
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    • 2017-09-22
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多