Authenticated GET of private google site image via ASP.Net

219 views Asked by At

I have a list of URLs of images that was taken from the content of a private google site (the part of the code used to get those urls is not important here, as it works as expected).

Having those URLs, I need to get the stream response of each one (I need a local copy of each), by using an authenticated GET request (because the google site is private).

This is how I authenticate and generate the access token:

var certificate = new X509Certificate2("c:/path/to/key.p12", "notasecret", X509KeyStorageFlags.Exportable);

var serviceAccountCredentialInitializer =
    new ServiceAccountCredential.Initializer("[email protected]")
    {
        Scopes = new[] { "http://sites.google.com/feeds/", 
                         "https://sites.google.com/feeds/" }
    }.FromCertificate(certificate);

var credential = new ServiceAccountCredential(serviceAccountCredentialInitializer);

if (!credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Result)
    throw new InvalidOperationException("Access token request failed.");

_accessToken = credential.Token.AccessToken;

And here's how I'm trying to request afterwards, with no luck (error 401 in the first using statement):

HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(imageUrl);
httpWebRequest.Headers.Add("Authorization", String.Format("Bearer {0}", _accessToken));

// error 401 on the next line
using (HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
    using (Stream stream = httpWebReponse.GetResponseStream())
    {
        var image = Image.FromStream(stream);
        ...
    }
}

UPDATE
I tried to make a GET using Google OAuth 2.0 Playground. If I try to get a feed, it works. But if I try to get an image, it also gives HTTP/1.1 401 Unauthorized

0

There are 0 answers