Reputation: 717
I'm following the Google Drive Api documentation that is at: https://developers.google.com/drive/v3/web/quickstart/dotnet
I've changed the folder to another specific folder.
string credPath = Server.MapPath(@"~\googleDrive");
credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
By the implemented form, the same permission will always be used (the first one), since it must be linked to the 'user' field.
user
field?user
field or the license path or both, for user x
not accessing user data y
?Upvotes: 0
Views: 2634
Reputation: 201
Thanks to https://stackoverflow.com/a/16168206/13513993 for the solution, you have to use Outh2 APIs:-
using Google.Apis.Oauth2.v2;
using Google.Apis.Oauth2.v2.Data;
Add scope (email):-
public static string[] Scopes = { Google.Apis.Drive.v3.DriveService.Scope.DriveReadonly, "email" };
You can get the credential from :-
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(FilePath, true)).Result;
}
Then use these functions:-
var oauthSerivce = new Oauth2Service(new BaseClientService.Initializer { HttpClientInitializer = credential });
UserInfo = oauthSerivce.Userinfo.Get().Execute();
Upvotes: 0
Reputation: 51
// Time-out in milliseconds, after which auth process will be terminated, whether permission granted or not
var timeoutMs = 60*1000;
var credCts = new CancellationTokenSource(timeoutMs);
var credPath = ".credentials/app-user-credentials"; //<-- In API refs ctor definead as FileDataStore(string folder, [bool fullPath = False]), credPath must be a folder name, not a file name as in your code
var authTask = GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecrets, Scopes, "someuniqueusername",
credCts.Token, new FileDataStore(credPath, true));
UserCredential credential = null;
try
{
if (authTask.Wait(timeoutMs, credCts.Token))
{
credential = authTask.Result;
}
else
{
throw new OperationCanceledException("Auth time-out");
}
}
catch (Exception ex)
{
Logger.Error(ex.Message);
throw;
}
finally
{
credCts.Dispose();
if (authTask.IsCanceled || authTask.IsCompleted || authTask.IsFaulted)
authTask.Dispose();
}
// do some stuff...
Update:
After you successfully received UserCredentials
(first time, or stored in FileDataStore
), to get authorized user email, you can use this function:
private static string GetUserEmail2(UserCredential credential)
{
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Name-Of-Your-Google-App",
});
var about = service.About.Get().Execute();
return about.User.EmailAddress;
}
Upvotes: 1