Search code examples
c#.netgoogle-cloud-platformgoogle-apigoogle-api-dotnet-client

Can OAuth2 be used in Google Cloud Client Libraries?


  • I would like to use .net variant of Google Cloud Client Libraries (Resource Manager for creating new project, for example).
  • I wouldn't like to use neither service account credentials nor ADC.

Can I somehow pass existing OAuth credentials (access token, obtained for appropriate scope) to the client library to authenticate the given user? (Or) do I need any authentication client library?

Briefly looked at the ProjectsClientBuilder class, but seems heavy generated (also as the documentation), meaning it's a bit harder to find any hint.


Solution

  • The following example shows how to authorize the Google cloud resource manager API using Oauth2 for an installed app.

    // Key file from google developer console (INSTALLED APP)
    var PathToInstalledKeyFile = @"C:\Development\FreeLance\GoogleSamples\Credentials\credentials.json";
    
    // scope of authorization needed for the method in question.
    var scopes = "https://www.googleapis.com/auth/cloud-platform";
    
    // Installed app authorizaton.
    var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.FromFile(PathToInstalledKeyFile).Secrets,
        new []{  scopes },
        "userName",
        CancellationToken.None,
        new FileDataStore("usercreds", true)).Result;
    
    var client = new ProjectsClientBuilder()
    {
        Credential = credential,
    }.Build();
    
    var projects = client.ListProjects(new FolderName("123"));
    

    Note for a web application the code will be different. Web authorization is not the same with the client library. I havent tried to connect any of the cloud apis via web oauth before.