C# .NET Google api 1.7测试版使用刷新令牌进行身份验证
我一直在研究Oauth.NETGoogleAPI,以便通过Oauth进行身份验证并使用GoogleDriveAPI 具体来说,我想使用已经存储的刷新令牌来实例化GoogleDrive服务 我找到了像这样的样品C# .NET Google api 1.7测试版使用刷新令牌进行身份验证,c#,google-drive-api,google-oauth,google-api-dotnet-client,C#,Google Drive Api,Google Oauth,Google Api Dotnet Client,我一直在研究Oauth.NETGoogleAPI,以便通过Oauth进行身份验证并使用GoogleDriveAPI 具体来说,我想使用已经存储的刷新令牌来实例化GoogleDrive服务 我找到了像这样的样品 这似乎使用了“GoogleWebAuthorizationBroker.AuthorizationAsync”,但我不确定如何将该方法用于刷新令牌,而不是您在本例中提供的客户端机密。client_secrets.json包含客户端ID和客户端机密(其中包含应用程序的OAuth 2.0信息
这似乎使用了“GoogleWebAuthorizationBroker.AuthorizationAsync”,但我不确定如何将该方法用于刷新令牌,而不是您在本例中提供的客户端机密。client_secrets.json包含客户端ID和客户端机密(其中包含应用程序的OAuth 2.0信息) 我认为本文将更好地解释如何使用OAuth 2.0访问Google Apps API,尤其是在构建web应用程序时
如果您对一个编码示例感兴趣,stackoverflow中有一个示例:如果我理解正确,您会问如何基于现有的刷新令牌创建新的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将根据您刷新的令牌和客户端机密获得一个新的访问令牌
请注意,此处必须包含客户端机密,否则将无法获取访问令牌。GoogleWebAuthorizationBroker要求您向其发送iDataStore的实施。在这种情况下,将发送FileDatastore。FileDataStore将数据存储在%appData%中。如果要使用保存在其他地方的refreshtoken,则需要创建自己的iDataStore 我在这里发布的实际数据存储的代码有点长 然后,您可以像使用文件数据存储一样使用它
//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;
}
该教程附带了一个示例项目。要使用刷新令牌:
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,因为它会在需要时自动启动web浏览器
找不到令牌。我更喜欢通过访问代码获取刷新令牌的老方法。
这与使用GoogleOAuthUtil.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));
几点意见。OAuth用于授权,而不是身份验证(尽管它有点像是作为副产品进行身份验证)。当您说“现有刷新令牌”时,请确保刷新令牌是使用适当的驱动器作用域生成的。由于您已经拥有刷新令牌,因此无需再次授权,因此您将不会使用GoogleWebAuthorizationBroker。我对.NET的了解不足以完全回答您的问题,但是从已经发布的答案来看,peleyal的答案是最接近的。谢谢大家。你给了我很多好的线索来跟进。我看到了filedatastore,并认为它可能包含一个刷新令牌,我只是找不到任何关于它的信息。谢谢你的链接谢谢艾米丽。我在过去看到并使用过这个代码示例,它确实起了作用。但使用“NativeApplicationClient”使用OAuth似乎是过时的方法。我想新的东西有全新的结构可以使用。再次感谢!这看起来确实接近我想要的。我会跟进的。我的应用程序设置有客户端机密。谢谢。这正是我所需要的,并且在我的代码中工作正常。非常感谢。对于最终来到这里的其他人,上面的方法取代了以前版本中的“IAAuthenticator”技术,该技术仍然是文档、示例应用程序等答案中的功能。您如何获得“您的\u刷新\u令牌\u此处”?如何从现有文件数据存储对象获取刷新令牌?