After tearing my hair out for the last two days I thought I would post my 
solution in getting this to work.  I could not get the Service Account 
solutions to work.  It would authenticate but when i pulled a list of 
albums it would return zero results and said I was forbidden to modify 
albums when adding photos.

tl:dr; I created a Web Application account and used that client id and 
client secret to get a refesh token using the OAuth2 Playground.  I then 
store that refresh token in my application (it never expires) to get new 
Access tokens whenever the application needs to authenticate.  Here are my 
steps below.  And by the way, you all own me one.... :)

*Google API OAuth2 Conversion*

*Setting up the new credentials*
1.     Log into the Google developers console:  
https://console.developers.google.com/project
 If the site already has a google account use the one stored in the 
web.config
2.    If there isn’t a project, click the Create Project button and give it 
a name
3.    If the left hand menu select Credentials under the APIs and auth menu
4.    Under the OAuth heading select Create New Client ID
5.    Make sure Application Type = Web Application and click the Create 
button
6.    Record the Client ID and the Client Secret (these will be added to 
the web.config)
7.    Under the newly created Client ID for web application, select the 
Edit settings button
8.    Add the following to the Authorized redirect URIs box: 
https://developers.google.com/oauthplayground
9.    Click Update
*Creating your Token*
10.     Open a new tab and go to the OAuth2 playground: 
https://developers.google.com/oauthplayground/
11.    Click the gear button in the top right (configuration)
12.    Change to the following settings

   - OAuth Flow: Server-side
   - OAuth endpoints: Google
   - The 2 Endpoint fields – leave alone
   - Access token location: Authorization header w/ Bearer prefix
   - Access Type: Offline
   - Force Approval Prompt: checked
   - Use you own OAuth credentials: checked
   - OAuth Client ID: Client ID that you created in step 6 above
   - OAuth Client secret: Client Secret you created in step 6 above

13.    Click the close link
14.    In the textbox for “Input your own scopes” paste the value: 
https://picasaweb.google.com/data/
15.    Select the Authorize APIs button
16.    Select the Accept button on the page that shows up
17.    This should take you to Step 2 in the OAuth playground
18.    Click the Exchange authorization code for tokens button
19.    The token boxes will fill in and take you to Step 3 in the 
playground.
20.    Select Step 2 on the left hand side and record the Refresh Token 
(this will be stored in the web.config file)

*Integration*
Add the following values to the web.config settings 
<add key="PicasaClientID" value="ClientID from step 6" />
<add key="PicasaClientSecret" value="Client secret from Step 6" />
<add key="PicasaToken" value="Refresh token from Step 20" />

*Code Logic*
Here is the new Authenticate function which will perform the authentication 
using Google OAuth 2.0 and associate it with the ps_Picasa Service class.  
Everything else will function as before.  The Access Token will be stored 
in the Application State and refreshed when it becomes expired using the 
Refresh Token.
private bool AuthenticatePicasaServiceNonAsync()
        {
            try
            {
                var requestFactory = new GDataRequestFactory("My App User 
Agent");

                if(!ValidateToken())
                {
                    GetNewAccessToken();
                }

                
requestFactory.CustomHeaders.Add(string.Format("Authorization: Bearer {0}", 
HttpContext.Current.Application["AccessToken"]));

                ps_Picasa = new PicasaService(str_PicasaApplicationName);
                ps_Picasa.RequestFactory = requestFactory;

                return true;
            }
            catch (Exception exc)
            {
                return false;
            }
        }
private void GetNewAccessToken()
        {
            try
            {
                string Url = "https://accounts.google.com/o/oauth2/token";;
                string grant_type = "refresh_token";
                //string redirect_uri_encode = 
UrlEncodeForGoogle(ReturnUrl);
                string data = 
"client_id={0}&client_secret={1}&refresh_token={2}&grant_type={3}";

                HttpWebRequest request = HttpWebRequest.Create(Url) as 
HttpWebRequest;
                string result = null;
                request.Method = "POST";
                request.KeepAlive = true;
                request.ContentType = "application/x-www-form-urlencoded";
                string param = string.Format(data, str_PicasaClientID, 
str_PicasaSecret, str_PicasaToken, grant_type);
                var bs = Encoding.UTF8.GetBytes(param);
                using (Stream reqStream = request.GetRequestStream())
                {
                    reqStream.Write(bs, 0, bs.Length);
                }

                using (WebResponse response = request.GetResponse())
                {
                    var sr = new StreamReader(response.GetResponseStream());
                    result = sr.ReadToEnd();
                    sr.Close();
                }

                var jsonSerializer = new JavaScriptSerializer();
                var TokenData = 
jsonSerializer.Deserialize<GoogleTokenModel>(result);

               

                HttpContext.Current.Application["AccessToken"] = 
TokenData.Access_Token;

            }
            catch
            {
                throw;
            }
        }

        private bool ValidateToken()
        {
            try
            {
            
                string apiURL = 
"https://www.googleapis.com/oauth2/v1/tokeninfo";;
                string data = "access_token={0}";

                HttpWebRequest request = HttpWebRequest.Create(apiURL) as 
HttpWebRequest;
                string result = null;
                request.Method = "POST";
                request.KeepAlive = true;
                request.ContentType = "application/x-www-form-urlencoded";
                string param = string.Format(data, 
HttpContext.Current.Application["AccessToken"]);
                var bs = Encoding.UTF8.GetBytes(param);
                using (Stream reqStream = request.GetRequestStream())
                {
                    reqStream.Write(bs, 0, bs.Length);
                }

                using (WebResponse response = request.GetResponse())
                {
                    var sr = new StreamReader(response.GetResponseStream());
                    result = sr.ReadToEnd();
                    sr.Close();
                }

                var jsonSerializer = new JavaScriptSerializer();
                var TokenData = 
jsonSerializer.Deserialize<GoogleTokenInfo>(result);

                if (string.IsNullOrEmpty(TokenData.error))
                {
                    if (TokenData.audience != str_PicasaClientID)
                        return false;

                    return true;
                }
                return false;
            }
            catch (Exception)
            {

                return false;
            }
        }

    }

    public class GoogleTokenModel
    {
        public string Access_Token { get; set; }
        public string Refresh_Token { get; set; }
        public string Expires_In { get; set; }
        public string Token_Type { get; set; }
    }

    public class GoogleTokenInfo
    {
        public string audience { get; set; }
        public string user_id { get; set; }
        public string scope { get; set; }
        public string expires_in { get; set; }
        public string error { get; set; }
    }








-- 
You received this message because you are subscribed to the Google Groups 
"Google Picasa Web Albums API" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/google-picasa-data-api.
For more options, visit https://groups.google.com/d/optout.

Reply via email to