我一直在查看Oauth .Net Google APIS,以便通过OAuth进行身份验证并使用Google驱动器API。
具体来说,我想使用已经存储的刷新令牌,以便使用它来实例化Google云端硬盘服务。
我找到了这样的样本https://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.SimpleOAuth2/Program.cs?repo=samples
这似乎使用"GoogleWebAuthorizationBroker.AuthorizeAsync",但我不确定如何将该方法与刷新令牌一起使用,而不是您在本例中似乎提供给它的客户端机密。
如果我理解正确,您是在问如何基于现有的刷新令牌创建新的Google服务。
因此,您可以执行以下操作:
var token = new TokenResponse { RefreshToken = "YOUR_REFRESH_TOKEN_HERE" };
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = [your_client_secrets_here]
}), "user", token);
然后,可以将凭据传递给服务的初始值设定项。
通过执行上述操作,GoogleAuthorizationCodeFlow 将根据刷新令牌和客户端机密获得新的访问令牌。
请注意,此处必须具有客户端机密,否则将无法获取访问令牌。
使用刷新令牌:
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文档中的说明进行操作。第一从谷歌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,文件夹内部是另一个包含refresh_token。
{
"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,因为它在以下情况下会自动启动Web浏览器找不到令牌。我更喜欢通过访问代码获取刷新令牌的老式方式。这与使用谷歌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));
client_secrets.json 包含客户端 ID 和客户端密钥(其中包含应用程序的 OAuth 2.0 信息)。
我认为本文将更好地解释如何通过OAuth 2.0访问Google Apps API,尤其是在构建Web应用程序时。
https://developers.google.com/accounts/docs/OAuth2WebServer
如果您对编码示例感兴趣,那么 stackoverflow 中有一个示例:Google+ API:如何使用 RefreshTokens 来避免每次启动应用时请求访问权限?
GoogleWebAuthorizationBroker要求您向其发送iDataStore的暗示,在这种情况下,将发送FileDatastore。 文件数据存储将数据存储在 %appData% 中。 如果要使用保存在其他地方的刷新令牌,则需要创建自己的 iDataStore 限制。
实际数据存储的代码我在这里发布有点长。 http://daimto.com/google-oauth2-csharp/
然后,您可以像使用文件数据存储一样使用它
//Now we load our saved refreshToken.
StoredResponse myStoredResponse = new StoredResponse(tbRefreshToken.Text);
// Now we pass a SavedDatastore with our StoredResponse.
using (var stream = new FileStream("client_secrets.json", FileMode.Open,
FileAccess.Read))
{
GoogleWebAuthorizationBroker.Folder = "Tasks.Auth.Store";
StoredCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { DriveService.Scope.Drive,
DriveService.Scope.DriveFile },
"user",
CancellationToken.None,
new SavedDataStore(myStoredResponse)).Result;
}
该教程附加了一个示例项目。