Sky*_*cer 4 c# google-api google-drive-api
我正在尝试通过Google drive OAuth2我的 C# 桌面应用程序验证我的登录。当用户输入Client ID和时Client secret,浏览器将打开并要求确认。当用户输入错误时,浏览器也会打开Client ID,并Client secret在 Google 网页上显示错误消息...
那么,如何在没有浏览器确认的情况下进行身份验证并在代码中处理所有 google OAuth2 错误并且无需任何浏览器页面?
这是我的验证码:
//...code
string[] scopes = new string[] { DriveService.Scope.Drive, DriveService.Scope.DriveFile };
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "WrongID",
ClientSecret = "WrongSecret"
},
scopes, _authUserName,
CancellationToken.None, new FileDataStore(_authDataStorePath, true)).Result;
//...code
Run Code Online (Sandbox Code Playgroud)
当这个块中发生错误时,代码的执行就会停止,什么也不会发生。
更新1:
好吧,假设我知道如何获取带有令牌的 json 文件。现在,我如何用这个文件创建 DriveService 对象?现在我创建它如下:
DriveService _drive = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential, // How to make this credential from tokens?
ApplicationName = _applicationName
});
Run Code Online (Sandbox Code Playgroud)
Google OAuth exceptions另外,捕获我的 C# 代码怎么样?现在,谷歌只是在浏览器中向我显示错误信息,而我的应用程序只是挂起......
ClientId 和 Client Secret 用于识别您的应用程序。这些需要硬编码或从数据库中提取,而不是由用户输入。至于没有打开 OAuth2 的浏览器。使用 API V3 就不能再这样做了,Google 已经弃用了所有以前的版本。
因此,如果您不想打开浏览器进行身份验证,则 Google Drive 有两种选择。如果您希望使用该应用程序的每个人共享 1 个 Google 驱动器,您可以设置一个服务帐户https://developers.google.com/accounts/docs/OAuth2ServiceAccount。
如果使用您的应用程序的每个人都将其安装在他们的设备上并使用自己的 Google 驱动器,您可以将其设置为具有离线/长期访问权限的已安装应用程序。谷歌并没有很好地记录这一点,但如果你搜索它,就会发现一些很好的例子。您将打开浏览器一次以获取该用户的刷新令牌,然后将其存储在数据库中,并且您将能够在他们每次登录时访问他们的驱动器,而无需打开浏览器。
这些是在没有浏览器的情况下执行此操作的唯一方法,Google 不再允许您向他们传递用户名和密码。
更新 -
你将需要这样的东西,这是用于离线的,但在线会类似。
string path = whereYouSaveClientSecret+ "client_secret.json";
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
StoredResponse myStoredResponse = new StoredResponse(RefreshToken);
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { DriveService.Scope.Drive},
"user",
CancellationToken.None,
new SavedDataStore(myStoredResponse)).Result;
}
DriveService _drive = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = _applicationName
});
Run Code Online (Sandbox Code Playgroud)
这是谷歌的示例https://developers.google.com/drive/web/examples/dotnet
| 归档时间: |
|
| 查看次数: |
10439 次 |
| 最近记录: |