Проблема в том, что приведенный выше пример не предназначен для ядра .net.
clientinfo.cs
/// <summary>
/// Client auth information, loaded from a Google user credential json file.
/// Set the TEST_CLIENT_SECRET_FILENAME environment variable to point to the credential file.
/// </summary>
public class ClientInfo
{
public static ClientInfo Load()
{
const string ClientSecretFilenameVariable = "TEST_CLIENT_SECRET_FILENAME";
string clientSecretFilename = Environment.GetEnvironmentVariable(ClientSecretFilenameVariable);
if (string.IsNullOrEmpty(clientSecretFilename))
{
throw new InvalidOperationException($"Please set the {ClientSecretFilenameVariable} environment variable before running tests.");
}
var secrets = JObject.Parse(Encoding.UTF8.GetString(File.ReadAllBytes(clientSecretFilename)))["web"];
var projectId = secrets["project_id"].Value<string>();
var clientId = secrets["client_id"].Value<string>();
var clientSecret = secrets["client_secret"].Value<string>();
return new ClientInfo(projectId, clientId, clientSecret);
}
private ClientInfo()
{
Load();
}
private ClientInfo(string projectId, string clientId, string clientSecret)
{
ProjectId = projectId;
ClientId = clientId;
ClientSecret = clientSecret;
}
public string ProjectId { get; }
public string ClientId { get; }
public string ClientSecret { get; }
}
Program.cs
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args)
{
var clientInfo = ClientInfo.Load();
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureServices(services =>
{
services.AddSingleton(clientInfo);
})
.Build();
}
}
startup.cs настроить службы
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "Google";
})
.AddCookie("Cookies")
.AddGoogleOpenIdConnect("Google", options =>
{
var clientInfo = (ClientInfo)services.First(x => x.ServiceType == typeof(ClientInfo)).ImplementationInstance;
options.ClientId = clientInfo.ClientId;
options.ClientSecret = clientInfo.ClientSecret;
options.Scope.Add("profile");
});
}
добавить следующее для настройки, а также app.UseAuthentication ();
контроллер
[GoogleScopedAuthorize("https://www.googleapis.com/auth/analytics.readonly")]
public async Task<IActionResult> GoogleAnalyticsReport([FromServices] IGoogleAuthProvider auth, [FromServices] ClientInfo clientInfo, long ViewId)
{
var cred = await auth.GetCredentialAsync();
var service = new AnalyticsReportingService(new BaseClientService.Initializer
{
HttpClientInitializer = cred
});
LogOut
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync();
return RedirectToAction("Index");
}
Теперь мой пользователь входит в систему, и я могу запрашивать данные.