Search code examples
google-oauthx509certificategoogle-api-dotnet-clientgoogle-maps-engine

Google Maps Engine Service Account with Google APIs .NET


I'm working on a service that requires authorization server to server to Google Maps Engine.

https://developers.google.com/maps-engine/documentation/oauth/serviceaccount and https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth?hl=en#service_account explains how to do this.

But, in the Google APIs. NET yet, do not have the class of service for Google Maps Engine API, then I would like to take part of the flow of the library, because I do not want to do all the hard work of managing JWT.

I think something like:

var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
    new ServiceAccountCredential.Initializer(serviceAccountEmail)
    {
        Scopes = new[] { "https://www.googleapis.com/auth/mapsengine" }
    }.FromCertificate(certificate));

var request = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/mapsengine/v1/projects");
credential.ApplyAuthenticationToRequest(request);

I want to use a pure HttpWebRequest, however using the certificate.

Could someone help me?

Alex


Solution

  • I'll recommend you to do the following:

    1. First of all use the Microsoft.Net.Http package. Google.Apis depends on it, so you already have it installed.

    2. Try to use the following code:

    // Create HTTP client using ConfigurableMessageHandler.
    // More details available in:
    http://contrib.google-api-dotnet-client.googlecode.com/hg/1.8.0-rc/documentation/classGoogle_1_1Apis_1_1Http_1_1ConfigurableMessageHandler.html.
    var httpClient = new HttpClientFactory().CreateHttpClient(new CreateHttpClientArgs
        {
            ApplicationName = "YOUR_APP_NAME",
        });
    // Add your credential as interceptor.
    httpClient.MessageHandler.ExecuteInterceptors.Add(credential);
    // Create the request.
    var response = await httpClient.GetAsync(
        "https://www.googleapis.com/mapsengine/v1/projects");
    

    I DIDN'T TEST it, but it should do the magic for you :)