.net core GoogleAPIsOAuth.NETCore3.1

.net core GoogleAPIsOAuth.NETCore3.1,.net-core,google-api,google-api-dotnet-client,.net Core,Google Api,Google Api Dotnet Client,我有一个.net core 3.1 MVC web应用程序。我正在尝试开始一些谷歌API。我发现谷歌文档非常混乱。在官方文档中,我发现一个MVC库不支持.net内核。有人能给我指出正确的方向吗?我应该如何开始在MVC.net核心web应用程序上验证我的用户?我应该寻找一个非谷歌oauth库吗?谷歌是否支持我找不到的东西 为了进一步挖掘,我遇到了Google.api.Auth.AspNetCore3。这是推荐的方法吗?关于如何使用它的任何文档,或者我应该自己下载源代码?我很困惑。您可以使用.NET

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


为了进一步挖掘,我遇到了Google.api.Auth.AspNetCore3。这是推荐的方法吗?关于如何使用它的任何文档,或者我应该自己下载源代码?我很困惑。

您可以使用.NET Core 3.1进行身份验证,它是谷歌维护和推荐的库。这是一个很好的示例(它只是一个ASP.NET Core 3 Web应用程序),说明了如何使用该库,并展示了它的所有功能。如果遇到任何问题,请随时在中创建问题。

这是Google analytics的一个示例。如果您需要帮助更改它以获得不同的api,请告诉我

startup.cs
公共类客户端
{
公共类网站
{
公共字符串客户端\u id{get;set;}
公共字符串客户端_secret{get;set;}
}
公共网站{get;set;}
}
公共类ClientInfo
{
公共客户端{get;set;}
专用只读IConfiguration\u配置;
公用客户端信息(IConfiguration配置)
{
_配置=配置;
Client=Load();
}
私有客户端加载()
{
var filePath=_配置[“测试WEB_客户端_机密_文件名”];
if(string.IsNullOrEmpty(filePath))
{
抛出新的InvalidOperationException(
$“请在运行测试之前设置TEST\u WEB\u CLIENT\u SECRET\u FILENAME环境变量。”);
}
如果(!File.Exists(filePath))
{
抛出新的InvalidOperationException(
$“请在运行测试之前设置TEST\u WEB\u CLIENT\u SECRET\u FILENAME环境变量。”);
}
var x=File.ReadAllText(文件路径);
返回JsonConvert.DeserializeObject(File.ReadAllText(filePath));
}
}
公营创业
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddSingleton();
services.AddControllers();
services.AddAuthentication(o=>
{
//这是为了挑战直接转到GoogleOpenID处理程序,因此没有
//需要添加一个AccountController,它会对登录发出挑战。
o、 DefaultChallengeScheme=GoogleOpenIdConnectDefaults.AuthenticationScheme;
//这是为了禁止直接访问GoogleOpenID处理程序,该处理程序检查
//需要额外的作用域并执行自动增量身份验证。
o、 DefaultBankeScheme=GoogleOpenIdConnectDefaults.AuthenticationScheme;
o、 DefaultScheme=CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogleOpenIdConnect(选项=>
{
var clientInfo=新的clientInfo(配置);
options.ClientId=clientInfo.Client.web.Client\u id;
options.ClientSecret=clientInfo.Client.web.Client\u secret;
});
services.AddMvc();
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(端点=>{endpoints.mapController();});
}
}
具有身份验证的控制器
[ApiController]
[路线(“[控制器]”)]
公共类GaA分析控制器:ControllerBase
{
专用只读ILogger\u记录器;
公共分析控制器(ILogger记录器)
{
_记录器=记录器;
}
//显示使用增量身份验证的测试。
//此属性表示必须在处理程序中授权列出的作用域。
[谷歌ScopedAuthorize(AnalyticsReportingService.ScopeConstants.AnalyticsReadonly)]
公共异步任务Get([FromServices]IGoogleAuthProvider身份验证,[FromServices]ClientInfo ClientInfo)
{
var GoogleAnalyticsViewId=“78110423”;
var cred=wait auth.GetCredentialAsync();
var服务=新的AnalyticsReportingService(新的BaseClientService.Initializer
{
HttpClientInitializer=cred
});
var dateRange=new dateRange
{
StartDate=“2015-06-15”,
EndDate=“2015-06-30”
};
//创建度量对象。
var会话=新度量
{
Expression=“ga:sessions”,
Alias=“会话”
};
//创建标注对象。
var browser=新维度
{
Name=“ga:浏览器”
};
//创建ReportRequest对象。
var reportRequest=新的reportRequest
{
ViewId=GoogleAnalyticsViewId,
DateRanges=新列表{dateRange},
维度=新Lis
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;
    }
}