此时,欢迎提供任何信息。我正在尝试通过 OAuth2 连接到 Google Drive API,但是当我运行我的凭据时:
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore("TokenStore"),
new LocalServerCodeReceiver(RedirectUri)).Result;
}
我总是收到此错误:
我遇到的问题是,每次调用该部分代码时,网址都会发生变化,因此无法在 GoogleCloud Console 中输入匹配的重定向网址。我已经尝试了一切,从 VS 静态设置端口,注册不同的身份验证 url,我检查了我的客户端 ID 和客户端密钥并完美匹配,此时我真的不知道该去哪里,因为我还没有去过能够以任何方式静态设置该 url。
有什么建议吗?
这是完整的代码:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DriveQuickstart
{
public class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-dotnet-quickstart.json
//follow this link
//https://developers.google.com/drive/v3/web/quickstart/dotnet
static string[] Scopes = { DriveService.Scope.DriveReadonly };
static string ApplicationName = "Drive API .NET Quickstart";
public static void Drive()
{
try
{
UserCredential credential;
const string RedirectUri = "http://localhost:61930/authorize/";
using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore("TokenStore"),
new LocalServerCodeReceiver(RedirectUri)).Result;
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
FilesResource.ListRequest listRequest = service.Files.List();
listRequest.PageSize = 10;
listRequest.Fields = "nextPageToken, files(id, name)";
// List files.
IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
.Files;
Console.WriteLine("Files:");
if (files != null && files.Count > 0)
{
foreach (var file in files)
{
Console.WriteLine("{0} ({1})", file.Name, file.Id);
}
}
else
{
Console.WriteLine("No files found.");
}
Console.Read();
}
catch (Exception e)
{
throw e;
}
}
}
}
我已经尝试了一切,显然问题是 url 是动态生成的,我无法使其静态,我不知道这是我的代码的一部分,还是可能是全局级别的项目中的某些内容,但是我已经从
appsettings.json
或 web.config
等以静态方式设置端口,但什么也没有,在验证凭据时它会重定向到另一个端口,谢谢大家!
问题主要是您有已安装/桌面应用程序的代码,但您正在将 client_secret.json 用于 Web 应用程序,这是错误的。去创建正确的凭证类型。
如果您确实想出于某种我不明白的原因使用网络凭据,您可以通过转到 Google 开发者控制台并按照此处所写的方式添加重定向 uri 来修复重定向 uri 错误