0

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("generated-service-email@developer.gserviceaccount.com")
    {
        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

zed
  • 2,298
  • 4
  • 27
  • 44
  • You need to authenticate yourself to get that resource. That's what the 401 error is telling you. – DavidG Jun 08 '15 at 23:58
  • I suggest you use a browser to authenticate and obtain the resource while capturing the http traffic, then compare the capture/logs to the http traffic that your app creates. See if there are any differences. – John Wu Jun 09 '15 at 00:00
  • @DavidG, there is the code where I authenticate and get the access token, any suggestions? – zed Jun 09 '15 at 12:37
  • @JohnWu, when I'm authenticated on a browser, and see the image, inspecting the traffic doesnt help much, because the header only have a cookie (which I assume it's doing the trick) – zed Jun 09 '15 at 18:32
  • So where in your code are you adding the cookie? – John Wu Jun 09 '15 at 19:14
  • I think we didn't understand: I need to make a simple HTTP get with the access token and nothing else, as the google documentation indicates when using OAuth2 and Service account. The cookie isn't needed (it is in the case of the browser because there is a user logged in gmail) – zed Jun 09 '15 at 19:49

0 Answers0