我通过反复试验找到了答案。需要注意的一件重要事情是服务器身份验证代码很快就会过期。如果您正在手动调试和复制粘贴,则在您运行代码之前,服务器验证码可能已经过期。在这种情况下,Google API 将“invalid_grant”作为错误返回,这对我来说是一种误导。
在我的示例解决方案中,您需要在项目中有一个文件“client_secret.json”,该文件在构建时复制到输出目录(文件属性->“构建操作”=“内容”,“复制到输出目录" = "始终复制")。
您从 Google API 控制台获取您的 client_secret.json 文件(https://console.developers.google.com/apis/credentials?project=,单击项目右侧“OAuth 2.0-Client-IDs”下的下载图标)。
重要提示:重定向 url 必须与项目中配置的重定向 url 匹配。对我来说,它只是空的,所以只需使用一个空字符串。
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Requests;
using System;
using System.IO;
using System.Reflection;
using System.Text;
namespace GoogleApiTest
{
// Source: https://developers.google.com/identity/sign-in/android/offline-access
class Program
{
static void Main(string[] args)
{
var authCode = "YOUR_FRESH_SERVER_AUTH_CODE";
var path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"client_secret.json");
var config = File.ReadAllText(path, Encoding.UTF8);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.Load(new FileStream(path, FileMode.Open));
var request = new AuthorizationCodeTokenRequest()
{
ClientId = clientSecrets.Secrets.ClientId,
ClientSecret = clientSecrets.Secrets.ClientSecret,
RedirectUri = "",
Code = authCode,
GrantType = "authorization_code"
};
var tokenResponse = request.ExecuteAsync(new System.Net.Http.HttpClient(), "https://www.googleapis.com/oauth2/v4/token", new System.Threading.CancellationToken(), Google.Apis.Util.SystemClock.Default).GetAwaiter().GetResult();
Console.ReadLine();
}
}
}