Tiedt Tech
Tiedt Tech

Reputation: 717

Google Drive Api get current user

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.

My Code

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.

My questions:

  1. How do I search for the current account logged into Google to put it in the user field?
  2. How do I if the user is not logged in, he can not access anything?
  3. Should I change the user field or the license path or both, for user x not accessing user data y?
  4. If on the permission screen as the image below, if the user close the browser or deny access, what is the best practice for the page not to be locked?

enter image description here

Upvotes: 0

Views: 2634

Answers (2)

Bilal Ur Rahman
Bilal Ur Rahman

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

LeffBA
LeffBA

Reputation: 51

  1. You don't have to look up the name of the current user to enter it here. "user" field - is just a shortcut name (part of file name) for the credential, which would be saved in file data store, does not matter what you will enter here, but it must be unique per file data store.
  2. If credential of user doesn't stored in file data store, or if user is not logged in, or logged but not grant permission for application - the application can't access to anything
  3. For each user, the Google drive of which you want to access, you must enter a unique name. Not quite clear on what the license path is it.
  4. You can try the code below, or best of all check with the google samples here
// 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

Related Questions