Google API Oauth .net core 3.1 [英] Google APIs Oauth .net core 3.1

查看:62
本文介绍了Google API Oauth .net core 3.1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a .net core 3.1 MVC web application. I'm trying to get started with some google apis. I'm finding Google documentation extremely confusing. In the official docs, I found was an MVC lib not supporting .net core. Can somebody point me in the right direction - how should I get started with authenticating my users on an MVC .net core web app? Should I be looking for a non google oauth lib? Does google support something that I'm not finding?

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

Trying to dig some more, I came across Google.Apis.Auth.AspNetCore3. Is this the recommended approach? Any documentation on how to use it, or I should be downloading source code myself? I'm plumb confused.

推荐答案

这是Google Analytics(分析)的一个示例,如果您需要更改其他api的帮助,请与我联系.

This is an example with Google analytics let me know if you need help altering it for a different api..

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

这篇关于Google API Oauth .net core 3.1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆