使用刷新令牌:
var init = new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "OAuth_Client_ID_From_GoogleAPI",
ClientSecret = "OAuth_Client_Secret"
},
Scopes = new string[] {"MY_SCOPES"}
};
var token = new TokenResponse { RefreshToken = "MY_REFRESH_TOKEN" };
var credential = new UserCredential(new Google.Apis.Auth.OAuth2.Flows.AuthorizationCodeFlow(init), "", token);
//init your Google API service, in this example Google Directory
var service = new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "",
});
如果您没有刷新令牌怎么办?最简单的方法是按照 Google SDK 文档上的说明进行操作。第一的
从 Google API 项目下载您的凭据。将文件命名为credentials.json。然后运行代码:
using (var stream =
new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
这应该创建一个文件夹 token.json 并且里面的文件夹是另一个包含你的 json 文件
刷新令牌。
{
"access_token" : "asdf",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "XXX",
"scope" : "https://www.googleapis.com/auth/admin.directory.user.readonly",
"Issued" : "2019-02-08T12:37:06.157-08:00",
"IssuedUtc" : "2019-02-08T20:37:06.157Z"
}
我不喜欢使用 GoogleWebAuthorizationBroker,因为它会在以下情况下自动启动网络浏览器
找不到令牌。我更喜欢通过访问代码获取刷新令牌的老式方法。
这与使用 Google OAuthUtil.CreateOAuth2AuthorizationUrl 和 OAuthUtil.GetAccessToken 非常相似
在 Google 的旧版 OAuth API 中。
var a = new Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "asdf",
ClientSecret = "hij"
},
Scopes = Scopes
};
var flow = new Google.Apis.Auth.OAuth2.Flows.AuthorizationCodeFlow(a);
var url = flow.CreateAuthorizationCodeRequest(GoogleAuthConsts.InstalledAppRedirectUri).Build().AbsoluteUri;
Console.WriteLine("Go to this URL and get access code: " + url);
Console.Write("Enter access code: ");
var code = Console.ReadLine();
Console.WriteLine("Fetching token for code: _" + code + "_");
var r = flow.ExchangeCodeForTokenAsync("user", code, GoogleAuthConsts.InstalledAppRedirectUri, CancellationToken.None).Result;
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(r));