Ejemplo n.º 1
0
        public ActionResult AuthorizationCheck(GoogleAPIAccess model)
        {
            if (model.AccessCode == null)
            {
                ////////////////////////////////////////////////////////////////////////////
                // STEP 3: Get the Authorization URL
                ////////////////////////////////////////////////////////////////////////////

                // Get the authorization url.  The user of your application must visit
                // this url in order to authorize with Google.  If you are building a
                // browser-based application, you can redirect the user to the authorization
                // url.
                model._RedirectURIs              = "urn:ietf:wg:oauth:2.0:oob";
                ViewData["authorizationUrl"]     = OAuthUtil.CreateOAuth2AuthorizationUrl(model);
                model._RedirectURIs              = Url.Action("AuthorizationCheckAuto", "Configuration", new { }, "http");
                ViewData["authorizationUrlAuto"] = OAuthUtil.CreateOAuth2AuthorizationUrl(model);
                return(View(model));
            }

            ////////////////////////////////////////////////////////////////////////////
            // STEP 4: Get the Access Token
            ////////////////////////////////////////////////////////////////////////////

            // Once the user authorizes with Google, the request token can be exchanged
            // for a long-lived access token.  If you are building a browser-based
            // application, you should parse the incoming request token from the url and
            // set it in OAuthParameters before calling GetAccessToken().
            model._RedirectURIs = "urn:ietf:wg:oauth:2.0:oob";
            OAuthUtil.GetAccessToken(model);
            return(RedirectToAction("Index", model));
        }
        private void setAuthorizationToken()
        {
            OAuthUtil.GetAccessToken(oAuth2Parameters);
            string accessToken = oAuth2Parameters.AccessToken;

            Console.WriteLine("OAuth Access Token: " + accessToken);
        }
Ejemplo n.º 3
0
        private void NGAMail()
        {
            //One time Initialization across the entire session required
            //if (authorizationUrl == null || authorizationUrl == string.Empty)
            //{
            string           CLIENT_ID     = "284081438460-sdg3dn9tt80huceeb9v4n833n97lmtlu.apps.googleusercontent.com";
            string           CLIENT_SECRET = "HNb2txJ2QpK0amd4IR7HAxZK";
            string           SCOPE         = "https://spreadsheets.google.com/feeds";
            string           REDIRECT_URI  = "urn:ietf:wg:oauth:2.0:oob";
            OAuth2Parameters parameters    = new OAuth2Parameters();

            parameters.ClientId     = CLIENT_ID;
            parameters.ClientSecret = CLIENT_SECRET;
            parameters.RedirectUri  = REDIRECT_URI;
            parameters.Scope        = SCOPE;
            authorizationUrl        = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);

            if (InputBox("AccessCode", "Input AccessCode from Browser", ref authorizationUrl) == DialogResult.OK)
            {
                parameters.AccessCode = authorizationUrl;
            }
            else
            {
                MessageBox.Show("Invallid Access Code!");
                btnConnectJenkins.Enabled = true;
                return;
            }

            OAuthUtil.GetAccessToken(parameters);
            GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "AlmJenkinsIntegration", parameters);

            spreadsheetsService.RequestFactory = requestFactory;
            //}
        }
Ejemplo n.º 4
0
        public static OAuth2Parameters Authorize()
        {
            var parameters = new OAuth2Parameters
            {
                ClientId     = ConfigurationManager.AppSettings.Get("Google-ClientID"),
                ClientSecret = ConfigurationManager.AppSettings.Get("Google-ClientSecret"),
                Scope        = "https://spreadsheets.google.com/feeds",
                RedirectUri  = "urn:ietf:wg:oauth:2.0:oob" //installed applications
            };

            var authUri = new Uri(OAuthUtil.CreateOAuth2AuthorizationUrl(parameters));

            using (var login = new GoogleLogin(authUri))
            {
                if (login.ShowDialog() != DialogResult.OK)
                {
                    return(null);
                }
                parameters.AccessCode = login.AccessCode;
            }

            try
            {
                OAuthUtil.GetAccessToken(parameters);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(null);
            }

            return(parameters);
        }
Ejemplo n.º 5
0
        public bool ShowAuthorizationDialog(bool isModal)
        {
            logger.Debug("ShowAuthorizationDialog {0}", isModal);
            string         sAuthorizationURL = OAuthUtil.CreateOAuth2AuthorizationUrl(AuthParams);
            GoogleAuthForm fAuthForm         = new GoogleAuthForm();

            fAuthForm.Url = sAuthorizationURL;
            if (isModal)
            {
                fAuthForm.ShowDialog();
            }
            else
            {
                fAuthForm.Show();
            }
            AuthResult arAuthResult = fAuthForm.Result ?? new AuthResult()
            {
                Result = ResultType.Denied, Value = string.Empty
            };

            logger.Info("Authorization Result={0}, Value={1}", arAuthResult.Result, arAuthResult.Value);

            if (arAuthResult.Result == ResultType.Success)
            {
                AuthParams.AccessCode = arAuthResult.Value;
                OAuthUtil.GetAccessToken(AuthParams);

                SaveAuthParams();

                return(true);
            }

            return(false);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// This console application demonstrates the usage of OAuth 2.0 with the Google Apps APIs.
        /// </summary>
        /// <param name="args">Command-line arguments: args[0] is
        /// the client ID, args[1] is the client secret, args[2] is domain name.
        /// </param>
        public static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine("Syntax: OAuth2Demo <client_id> <client_secret> <domain>");
            }
            else
            {
                clientId     = args[0];
                clientSecret = args[1];
                domain       = args[2];

                OAuth2Parameters parameters = new OAuth2Parameters()
                {
                    ClientId     = clientId,
                    ClientSecret = clientSecret,
                    RedirectUri  = redirectUri,
                    Scope        = scopes
                };

                string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
                Console.WriteLine("Authorize URI: " + url);
                parameters.AccessCode = Console.ReadLine();

                OAuthUtil.GetAccessToken(parameters);

                // Testing OAuth 2.0 with a Request-based library
                RunContactsSample(parameters);

                // Testing OAuth 2.0 with a Service-based library
                RunGroupsSample(parameters, domain);
            }
        }
Ejemplo n.º 7
0
        public static void Authorize(OAuth2Parameters parameters)
        {
            //parameters.RedirectUri = "urn:ietf:wg:oauth:2.0:oob";

            parameters.RedirectUri = "http://localhost:8080";
            string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);

            var listener = new HttpListener();

            listener.Prefixes.Add("http://localhost:8080/");
            listener.Start();
            var contextAsync = listener.GetContextAsync();

            System.Diagnostics.Process.Start(authorizationUrl);

            contextAsync.Wait();
            parameters.AccessCode = contextAsync.Result.Request.QueryString["code"];

            HttpListenerResponse response = contextAsync.Result.Response;
            // Construct a response.
            string responseString = "<HTML><head><script>window.open('', '_self', ''); /* bug fix chrome*/ window.close();</script></head></HTML>";

            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            // Get a response stream and write the response to it.
            response.ContentLength64 = buffer.Length;
            System.IO.Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            // You must close the output stream.
            output.Close();
            listener.Stop();

            //http://stackoverflow.com/questions/12077455/gdata-oauthutil-getaccesstoken-does-not-return-a-refresh-token-value
            OAuthUtil.GetAccessToken(parameters);
        }
 public void Second(string someAccessCode)
 {
     // I want to reuse the above OAuth2Parameters parameters here:
     parameters.AccessCode = someAccessCode;
     OAuthUtil.GetAccessToken(parameters);
     string accessToken = parameters.AccessToken;
 }
Ejemplo n.º 9
0
        private void GetAccessCode(object sender, NavigationEventArgs e)
        {
            mshtml.IHTMLDocument2 doc = LoginBrowser.Document as mshtml.IHTMLDocument2;
            string accessCode         = doc.title;

            if (accessCode.Substring(0, 7) == "Success")
            {
                accessCode            = accessCode.Remove(0, 13);
                parameters.AccessCode = accessCode;// Key.Text;
                OAuthUtil.GetAccessToken(parameters);
                string accessToken = parameters.AccessToken;

                GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "BoardGameStats", parameters);
                service.RequestFactory = requestFactory;

                if (service != null)
                {
                    DialogResult = true;
                }
                else
                {
                    DialogResult = false;
                }
            }
        }
Ejemplo n.º 10
0
    public void GetAccessToken()
    {
        /*
         * https://github.com/kimsama/Unity-QuickSheet/blob/50dfaed0397c511ac9da9ee42f64143b3a63e02e/Assets/QuickSheet/GDataPlugin/Editor/GDataDB/GDataDB/Impl/GDataDBRequestFactory.cs#L104-L122
         */
        Init();
        OAuth2Parameters parameters = new OAuth2Parameters();

        parameters.ClientId     = CLIENT_ID;
        parameters.ClientSecret = CLIENT_SECRET;
        parameters.RedirectUri  = REDIRECT_URI;

        parameters.Scope      = SCOPE;
        parameters.AccessType = "offline";  // IMPORTANT
        parameters.TokenType  = TOKEN_TYPE; // IMPORTANT

        parameters.AccessCode = ACCESS_CODE;

        OAuthUtil.GetAccessToken(parameters);
        OAuthUtil.RefreshAccessToken(parameters);

        ACCESS_TOKEN  = parameters.AccessToken;
        REFRESH_TOKEN = parameters.RefreshToken;

        EditorUtility.SetDirty(this);
    }
        public ActionResult SubmitAuthorize(string code)
        {
            string           REDIRECT_URI = "http://localhost:11551" + Url.Action("SubmitAuthorize", new { controller = "photoshop", area = "admin" });
            OAuth2Parameters parameters   = new OAuth2Parameters
            {
                ClientId     = CLIENT_ID,
                ClientSecret = CLIENT_SECRET,
                RedirectUri  = REDIRECT_URI,
                Scope        = SCOPE,
                AccessCode   = code
            };

            OAuthUtil.GetAccessToken(parameters);
            string accessToken = parameters.AccessToken;
            var    shet        = _context.GoogleSheetsSync.Find(Guid.Empty);

            if (shet == null)
            {
                shet = new GoogleSheetsSync()
                {
                    ID           = Guid.Empty,
                    Token        = accessToken,
                    RefreshToken = parameters.RefreshToken
                };
                _context.GoogleSheetsSync.Add(shet);
            }
            else
            {
                shet.Token        = accessToken;
                shet.RefreshToken = parameters.RefreshToken;
            }
            _context.SaveChanges();
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 12
0
    void GetAccessCode()
    {
        // OAuth2Parameters holds all the parameters related to OAuth 2.0.
        OAuth2Parameters parameters = new OAuth2Parameters();

        parameters.ClientId = CLIENT_ID;

        parameters.ClientSecret = CLIENT_SECRET;

        parameters.RedirectUri = REDIRECT_URI;

        // Get the Authorization URL
        parameters.Scope = SCOPE;

        parameters.AccessType = "offline";         // IMPORTANT and was missing in the original

        parameters.TokenType = TOKEN_TYPE;         // IMPORTANT and was missing in the original

        // Authorization url.

        string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);

        Debug.Log(authorizationUrl);
        Debug.Log("Please visit the URL above to authorize your OAuth "
                  + "request token.  Once that is complete, type in your access code to "
                  + "continue...");

        parameters.AccessCode = accessCode;

        if (parameters.AccessCode == "")
        {
            Debug.LogWarning("Access code is blank!");
            EditorUtility.ClearProgressBar();
            Application.OpenURL(authorizationUrl);
            return;
        }

        Debug.Log("Get access token.");

        // Get the Access Token
        try{
            OAuthUtil.GetAccessToken(parameters);
            string accessToken  = parameters.AccessToken;
            string refreshToken = parameters.RefreshToken;
            Debug.Log("OAuth Access Token: " + accessToken + "\n");
            ACCESS_TOKEN = accessToken;
            Debug.Log("OAuth Refresh Token: " + refreshToken + "\n");
            REFRESH_TOKEN = refreshToken;
            PlayerPrefs.SetString(PREF_ACCESS_CODE, accessCode);
            PlayerPrefs.Save();
            DownloadToJson();
        }
        catch (System.Exception e)
        {
            Debug.LogError(e.ToString());
            EditorUtility.ClearProgressBar();
            Application.OpenURL(authorizationUrl);
            return;
        }
    }
        public static void FinishAuthenticate(GoogleSettings googleSettings)
        {
            try {
                OAuth2Parameters parameters = new OAuth2Parameters();
                parameters.ClientId     = googleSettings.authInfo.client_id;
                parameters.ClientSecret = googleSettings.authInfo.client_secret;
                parameters.RedirectUri  = googleSettings.authInfo.GetRedirectURI();

                parameters.Scope      = SCOPE;
                parameters.AccessType = "offline";  // IMPORTANT
                parameters.TokenType  = TOKEN_TYPE; // IMPORTANT

                parameters.AccessCode = googleSettings.accessCode;

                OAuthUtil.GetAccessToken(parameters);
                string accessToken  = parameters.AccessToken;
                string refreshToken = parameters.RefreshToken;
                //Debug.Log("OAuth Access Token: " + accessToken + "\n");
                //Debug.Log("OAuth Refresh Token: " + refreshToken + "\n");

                googleSettings.refreshToken = refreshToken;
                googleSettings.accessToken  = accessToken;
            }
            catch (Exception e) {
                // To display the error message with EditorGUI.Dialogue, we throw it again.
                throw new Exception(e.Message);
            }
        }
        public static void FinishAuthenticate(GoogleDataSettings settings)
        {
            try
            {
                OAuth2Parameters parameters = new OAuth2Parameters()
                {
                    ClientId     = settings.OAuth2Data.client_id,
                    ClientSecret = settings.OAuth2Data.client_secret,
                    RedirectUri  = REDIRECT_URI,

                    Scope      = SCOPE,
                    AccessType = "offline",  // IMPORTANT
                    TokenType  = TOKEN_TYPE, // IMPORTANT

                    AccessCode = settings._AccessCode
                };
                OAuthUtil.GetAccessToken(parameters);
                string accessToken  = parameters.AccessToken;
                string refreshToken = parameters.RefreshToken;
                //Debug.Log("OAuth Access Token: " + accessToken + "\n");
                //Debug.Log("OAuth Refresh Token: " + refreshToken + "\n");

                settings._RefreshToken = refreshToken;
                settings._AccessToken  = accessToken;
            }
            catch (Exception e)
            {
                // To display the error message with EditorGUI.Dialogue, we throw it again.
                throw new Exception(e.Message);
            }
        }
Ejemplo n.º 15
0
        public bool SignIn(string accessCode)
        {
            try
            {
                parameters            = GetRawOAuth2Parameters();
                parameters.AccessCode = accessCode;

                // 同期WebRequest通信が中で走る.
                OAuthUtil.GetAccessToken(parameters);

                SpreadsheetConnectorPrefs.accessTokenKey  = parameters.AccessToken;
                SpreadsheetConnectorPrefs.refreshTokenKey = parameters.RefreshToken;
                SpreadsheetConnectorPrefs.tokenExpiryKey  = parameters.TokenExpiry.ToString();

                service = CreateService(parameters);

                State = AuthenticationState.SignIn;
                return(true);
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
                SignOut();
                return(false);
            }
        }
        public void Connect()
        {
            if (_parameters.AccessCode == null)
            {
                throw new InvalidOperationException("No access code set.");
            }


            ////////////////////////////////////////////////////////////////////////////
            // STEP 4: Get the Access Token
            ////////////////////////////////////////////////////////////////////////////

            // Once the user authorizes with Google, the request token can be exchanged
            // for a long-lived access token.  If you are building a browser-based
            // application, you should parse the incoming request token from the url and
            // set it in OAuthParameters before calling GetAccessToken().
            OAuthUtil.GetAccessToken(_parameters);
            string accessToken = _parameters.AccessToken;

            Console.WriteLine("OAuth Access Token: " + accessToken);

            ////////////////////////////////////////////////////////////////////////////
            // STEP 5: Make an OAuth authorized request to Google
            ////////////////////////////////////////////////////////////////////////////

            // Initialize the variables needed to make the request
            GOAuth2RequestFactory requestFactory =
                new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", _parameters);

            _service = new SpreadsheetsService("MySpreadsheetIntegration-v1");
            _service.RequestFactory = requestFactory;

            // Make the request to Google
            // See other portions of this guide for code to put here...
        }
Ejemplo n.º 17
0
        public IAccountSettings TestAccount(IAccountSettings accountnForTest)
        {
            parameters.ClientId     = Constants.googleSheetsCLIENT_ID;
            parameters.ClientSecret = Constants.googleSheetsCLIENT_SECRET;
            parameters.RedirectUri  = Constants.googleSheetsREDIRECT_URI;
            parameters.Scope        = Constants.googleSheetsSCOPE;

            GoogleSheetsAccountSettings accountForTestGS = (GoogleSheetsAccountSettings)accountnForTest;
            GoogleSheetsAccountToken    tokenForTest     = accountForTestGS.Tokens.First();
            Boolean result = false;

            if (tokenForTest != null)
            {
                foreach (GoogleSheetsAccountToken gast in accountForTestGS.Tokens)
                {
                    if (gast.TokenName == "GetNewToken")
                    {
                        string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
                        gast.RefreshToken = authorizationUrl;
                    }
                    else if (gast.TokenName == "EnterAccessToken")
                    {
                        parameters.AccessToken = gast.RefreshToken;
                        parameters.AccessCode  = gast.RefreshToken;
                        OAuthUtil.GetAccessToken(parameters);
                        gast.RefreshToken = parameters.RefreshToken;
                    }
                    else if (gast.TokenName == "UseSaveToken")
                    {
                        parameters.AccessToken  = gast.RefreshToken;
                        parameters.AccessCode   = gast.RefreshToken;
                        parameters.RefreshToken = gast.RefreshToken;
                        OAuthUtil.RefreshAccessToken(parameters);
                    }
                    else if (gast.TokenName == "CheckFileName")
                    {
                        parameters.AccessToken  = accountForTestGS.Tokens[0].RefreshToken;
                        parameters.AccessCode   = accountForTestGS.Tokens[0].RefreshToken;
                        parameters.RefreshToken = accountForTestGS.Tokens[0].RefreshToken;
                        bool result2;
                        result2 = CheckFileGS(gast.RefreshToken, accountForTestGS);
                        if (!result2)
                        {
                            gast.RefreshToken = "This file does not exist";
                        }
                        else
                        {
                            gast.RefreshToken = "OK";
                        }
                    }
                }

                result = true;
            }

            accountForTestGS.TestResult = result;
            return(accountForTestGS);
        }
Ejemplo n.º 18
0
        public static void getAccessTokens(string clientId, string clientSecret, string accessCode, out string accessToken, out string refreshToken)
        {
            OAuth2Parameters parameters = getOAuth2Parameters(clientId, clientSecret, accessCode);

            OAuthUtil.GetAccessToken(parameters);

            accessToken  = parameters.AccessToken;
            refreshToken = parameters.RefreshToken;
        }
Ejemplo n.º 19
0
 public void SetAccessCode(string code)
 {
     if (oauth2Params != null)
     {
         oauth2Params.AccessCode = code;
         OAuthUtil.GetAccessToken(oauth2Params);
         SaveTokens();
     }
 }
Ejemplo n.º 20
0
        private async Task <DialogResult> GetGoogleService(Action <string, string> setPath)
        {
            if (_googleDocGenerator == null)
            {
                OAuth2Parameters parameters = new OAuth2Parameters
                {
                    ClientId     = "261863669828-1k61kiqfjcci0psjr5e00vcpnsnllnug.apps.googleusercontent.com",
                    ClientSecret = "IDtucbpfYi3C7zWxsJUX4HbV",
                    RedirectUri  = "urn:ietf:wg:oauth:2.0:oob",
                    Scope        = "https://spreadsheets.google.com/feeds https://docs.google.com/feeds",
                    ResponseType = "code"
                };
                string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);

                var browserDialog = new BrowserDialog(TimeSpan.FromSeconds(30), new Uri(authorizationUrl));

                try
                {
                    if (await browserDialog.ShowAsync(code => parameters.AccessCode = code) != DialogResult.OK)
                    {
                        return(DialogResult.Cancel);
                    }
                }
                catch (Exception e)
                {
                    ShowDialogWindow(DialogIcon.Critical, DialogRes.Exception, e.ToString());

                    throw;
                }

                OAuthUtil.GetAccessToken(parameters);

                _googleOAuth2Parameters = parameters;

                var service = new SpreadsheetsService("MySpreadsheetIntegration-v1")
                {
                    RequestFactory = new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", parameters)
                };

                _googleDocGenerator = new GoogleDocGenerator(service);
            }
            else
            {
                if (_googleOAuth2Parameters.TokenExpiry <= DateTime.Now)
                {
                    OAuthUtil.RefreshAccessToken(_googleOAuth2Parameters);
                }
            }

            SelectGoogleDocumentDialog selectDocumentDialog = new SelectGoogleDocumentDialog(_showDialogAction, _googleDocGenerator);

            DialogResult dialogResult = await selectDocumentDialog.ShowAsync(setPath);

            return(dialogResult);
        }
Ejemplo n.º 21
0
        public GoogleAuthDTO GetToken(string code)
        {
            var parameters = CreateOAuth2Parameters(accessCode: code);

            OAuthUtil.GetAccessToken(parameters);
            return(new GoogleAuthDTO()
            {
                AccessToken = parameters.AccessToken,
                Expires = parameters.TokenExpiry,
                RefreshToken = parameters.RefreshToken
            });
        }
        public void FinishAuthenticate()
        {
            OAuth2Parameters parameters = GetParameters();

            OAuthUtil.GetAccessToken(parameters);

            string accessToken  = parameters.AccessToken;
            string refreshToken = parameters.RefreshToken;

            Debug.Log("OAuth Access Token: " + accessToken);
            Debug.Log("OAuth Refresh Token: " + refreshToken);
        }
Ejemplo n.º 23
0
    public ActionResult Oauth()
    {
        // retrieve and update the tokens for temporary authentication
        OAuthParameters parameters = BuildParameters();

        OAuthUtil.UpdateOAuthParametersFromCallback(Request.Url.Query, parameters);
        // finally, get the token we need b@#$!!!
        OAuthUtil.GetAccessToken(parameters);
        // save those tokens into the database
        SaveParametersTokens(parameters);
        // all the success in the world, return back
        return(RedirectToAction("Index", "Admin"));
    }
Ejemplo n.º 24
0
        public string AuthWithAccessCode(string accessCode)
        {
            OAuth2Parameters parameters = new OAuth2Parameters();

            parameters.ClientId     = Config.CLIENT_ID;
            parameters.ClientSecret = Config.CLIENT_SECRET;
            parameters.RedirectUri  = REDIRECT_URI;
            parameters.Scope        = SCOPE;
            parameters.AccessCode   = accessCode;

            OAuthUtil.GetAccessToken(parameters);
            return(parameters.RefreshToken);
        }
Ejemplo n.º 25
0
        private void googleDriveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_Gmail == null || _Gpass == null)
            {
                ToErrorLog("Отсутствие данных", "Авторизация Google", "Ключ не содержал данных!");
                return;
            }
            parameters.ClientId = CLIENT_ID;

            parameters.ClientSecret = CLIENT_SECRET;

            parameters.RedirectUri = REDIRECT_URI;

            ////////////////////////////////////////////////////////////////////////////
            // STEP 3: Get the Authorization URL
            ////////////////////////////////////////////////////////////////////////////

            // Set the scope for this particular service.
            parameters.Scope = SCOPE;

            // Get the authorization url.  The user of your application must visit
            // this url in order to authorize with Google.  If you are building a
            // browser-based application, you can redirect the user to the authorization
            // url.
            string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
            //System.Diagnostics.Process.Start(authorizationUrl);
            Authentication auth = new Authentication();

            auth.URL   = authorizationUrl;
            auth.Gpass = _Gpass;
            auth.Gmail = _Gmail;
            auth.ShowDialog();
            if (auth.Key != null)
            {
                parameters.AccessCode = auth.Key;
                OAuthUtil.GetAccessToken(parameters);
                string accessToken = parameters.AccessToken;
                GOAuth2RequestFactory requestFactory =
                    new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", parameters);
                service = new SpreadsheetsService("MySpreadsheetIntegration-v1");
                service.RequestFactory = requestFactory;
                GooglePicture.Image    = Properties.Resources.googleDrive as Bitmap;
                GoogleToolTip.SetToolTip(this.GooglePicture, "Доступ к Google Disk\nразрешен.");
            }
            else
            {
                MessageBox.Show("Вход не выполнен", "Google Service Access", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            ToLog("Авторизация Google", string.Format(auth.Info));
            auth.Close();
        }
Ejemplo n.º 26
0
        private static OAuth2Parameters GetAccessToken(HttpContext context, string scope)
        {
            string url             = context.Request.Url.ToString();
            string urlWithProvider = CreateGoogleProvderRequestUrl(url);
            string accessCode      = GetAccessCode(context.Request);

            OAuth2Parameters parameters = CreateAuthorizationParameters(scope);

            parameters.RedirectUri = urlWithProvider;
            parameters.AccessCode  = accessCode;

            OAuthUtil.GetAccessToken(parameters);

            return(parameters);
        }
Ejemplo n.º 27
0
        private void AskAccessCode()
        {
            // Ask to get the authorization code. Give the URL and ask for the code.
            string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(oauthParams);

            Console.WriteLine("Please open the following link in a browser and authorize");
            Console.WriteLine("yourself on the webpage. Once that is complete, type");
            Console.WriteLine("your access code and press Enter to continue.");
            Console.WriteLine(authorizationUrl);

            Console.Write("Access code: ");
            oauthParams.AccessCode = Console.ReadLine();
            Console.WriteLine("-----------------------------------------");
            Console.WriteLine();

            OAuthUtil.GetAccessToken(oauthParams);
        }
Ejemplo n.º 28
0
 /// <summary>
 /// 認証
 /// </summary>
 /// <param name="authCode"></param>
 /// <returns></returns>
 public bool Autorize(string authCode)
 {
     Properties.Settings.Default.GSRefreshToken = "";
     _parameters.AccessCode = authCode;
     try
     {
         OAuthUtil.GetAccessToken(_parameters);
     }
     catch (System.Net.WebException ex)
     {
         //認証失敗だお
         System.Diagnostics.Debug.WriteLine("Authorize ex:" + ex.ToString());
         return(false);
     }
     Properties.Settings.Default.GSRefreshToken = _parameters.RefreshToken;
     return(true);
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Prepare class for request with specified credentials
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        //public bool Logon()
        //{
        //}

        /// <summary>
        /// Authorize request
        /// </summary>
        /// <param name="AuthorizeCode">Write authorize Code from Web pages</param>
        /// <returns>True if success authorize</returns>
        public bool AuthorizeSession(string AuthorizeCode)
        {
            LoggerProvider.Instance.Logger.Debug("Try authorize google request with access code from web. Access code is: {0}", AuthorizeCode);
            OAuth20.AccessCode = AuthorizeCode;
            _isLogon           = false;
            try
            {
                OAuthUtil.GetAccessToken(OAuth20);
                _isLogon = true;
            }
            catch (WebException we)
            {
                LoggerProvider.Instance.Logger.Error("Google Authorize Token not alid.");
                LoggerProvider.Instance.Logger.Error(we);
            }
            return(_isLogon);
        }
        static void Main(string[] args)
        {
            string CLIENT_ID     = "YOUR_CLIENT_ID";
            string CLIENT_SECRET = "YOUR_CLIENT_SECRET";
            string SCOPE         = "https://spreadsheets.google.com/feeds https://docs.google.com/feeds";
            string REDIRECT_URI  = "urn:ietf:wg:oauth:2.0:oob";

            OAuth2Parameters parameters = new OAuth2Parameters();

            parameters.ClientId     = CLIENT_ID;
            parameters.ClientSecret = CLIENT_SECRET;
            parameters.RedirectUri  = REDIRECT_URI;
            parameters.Scope        = SCOPE;

            string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);

            MessageBox.Show(authorizationUrl);
            Console.WriteLine("Please visit the URL in the message box to authorize your OAuth "
                              + "request token.  Once that is complete, type in your access code to "
                              + "continue...");
            parameters.AccessCode = Console.ReadLine();

            OAuthUtil.GetAccessToken(parameters);
            string accessToken = parameters.AccessToken;

            Console.WriteLine("OAuth Access Token: " + accessToken);

            GOAuth2RequestFactory requestFactory =
                new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", parameters);
            SpreadsheetsService service = new SpreadsheetsService("MySpreadsheetIntegration-v1");

            service.RequestFactory = requestFactory;

            SpreadsheetQuery query = new SpreadsheetQuery();

            SpreadsheetFeed feed = service.Query(query);

            // Iterate through all of the spreadsheets returned
            foreach (SpreadsheetEntry entry in feed.Entries)
            {
                // Print the title of this spreadsheet to the screen
                Console.WriteLine(entry.Title.Text);
            }
            Console.ReadLine();
        }