示例#1
0
        private cGoogle()
        {
            // Register the authenticator. The Client ID and secret have to be copied from the API Access
            // tab on the Google APIs Console.
            provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
            provider.ClientIdentifier = "528532804655.apps.googleusercontent.com";
            provider.ClientSecret = "9QSFSAg0dE5CqC5F_Ot6MD8f";

            // Get the auth URL:
            state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() });
            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            Uri authUri = provider.RequestUserAuthorization(state);

            // Request authorization from the user (by opening a browser window):
            Process.Start(authUri.ToString());
            // Initialize background workers
            authWorker = new BackgroundWorker();
            fetchWorker = new BackgroundWorker();
            authWorker.WorkerReportsProgress = true;
            authWorker.WorkerSupportsCancellation = true;
            authWorker.DoWork += new DoWorkEventHandler(authWorker_DoWork);
            authWorker.ProgressChanged += new ProgressChangedEventHandler(authWorker_ProgressChanged);
            fetchWorker.WorkerReportsProgress = true;
            fetchWorker.WorkerSupportsCancellation = true;
            fetchWorker.DoWork += new DoWorkEventHandler(fetchWorker_DoWork);
            fetchWorker.ProgressChanged += new ProgressChangedEventHandler(fetchWorker_ProgressChanged);
        }
示例#2
0
        private IAuthorizationState GetAuthorization(NativeApplicationClient arg)
        {
            // Get the auth URL:
            _state = new AuthorizationState(new[] {DriveService.Scopes.Drive.GetStringValue()});
            _state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            Uri authUri = arg.RequestUserAuthorization(_state);

            //Show Login UI. It's tip for user 
            var dlg = new AuthDlg(StorageType.GDrive);
            dlg.Top = 0;
            dlg.Show();

            // Request authorization from the user (by opening a browser window):
            //Process.Start(authUri.ToString());    
            _webViewCallback(authUri.ToString());

            dlg.Close(); //close non-modal stub dialog 

            //open another, modal dialog to block execution until user clicks OK
            dlg = new AuthDlg(StorageType.GDrive) {Top = 0};
            dlg.ShowDialog();

            // Retrieve the access token by using the authorization code:
            return arg.ProcessUserAuthorization(dlg.AuthCode, _state);
        }
        public void RequestUserAuthorizationTest()
        {
            var client = new NativeApplicationClient(GoogleAuthenticationServer.Description);
            client.ClientIdentifier = "Test";
            client.ClientSecret = "123";

            // Check that the callback URL is set correctly. We test this, as the Out of Band URI is required
            // for most cases of the Native-Application flow.
            Assert.IsTrue(
                client.RequestUserAuthorization().ToString().Contains(NativeApplicationClient.OutOfBandCallbackUrl));
        }
示例#4
0
文件: Program.cs 项目: sunpander/VSDT
 private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
 {
     // Get the auth URL:
     IAuthorizationState state = new AuthorizationState(new[] { TasksService.Scopes.Tasks.GetStringValue() });
     state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
     Uri authUri = arg.RequestUserAuthorization(state);
     // Request authorization from the user (by opening a browser window):
     Process.Start(authUri.ToString());
     Console.Write("  Authorization Code: ");
     string authCode = Console.ReadLine();
     Console.WriteLine();
     // Retrieve the access token by using the authorization code:
     return arg.ProcessUserAuthorization(authCode, state);
 }
        public static string GetAuthorizationUrl(string emailAddress)
        {
            var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, _clientId, _clientSecret);
            IAuthorizationState authorizationState = new AuthorizationState(_scopes);
            authorizationState.Callback = new Uri(_redirectUri);

            UriBuilder builder = new UriBuilder(provider.RequestUserAuthorization(authorizationState));
            NameValueCollection queryParameters = HttpUtility.ParseQueryString(builder.Query);

            queryParameters.Set("access_type", "offline");
            queryParameters.Set("approval_prompt", "force");
            queryParameters.Set("user_id", emailAddress);

            builder.Query = queryParameters.ToString();
            return builder.Uri.ToString();
        }
        public mGoogle()
        {
            // Register the authenticator. The Client ID and secret have to be copied from the API Access
            // tab on the Google APIs Console.
            provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
            provider.ClientIdentifier = "528532804655.apps.googleusercontent.com";
            provider.ClientSecret = "9QSFSAg0dE5CqC5F_Ot6MD8f";

            // Get the auth URL:
            state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() });
            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            Uri authUri = provider.RequestUserAuthorization(state);

            // Request authorization from the user (by opening a browser window):
            Process.Start(authUri.ToString());
        }
示例#7
0
    /// <summary>
    /// Retrieve the authorization URL.
    /// </summary>
    /// <param name="emailAddress">User's e-mail address.</param>
    /// <param name="state">State for the authorization URL.</param>
    /// <returns>Authorization URL to redirect the user to.</returns>
    public static String GetAuthorizationUrl(String emailAddress, String state)
    {
        var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
        provider.ClientIdentifier = CLIENT_ID;

        IAuthorizationState authorizationState = new AuthorizationState(SCOPES);
        authorizationState.Callback = new Uri(REDIRECT_URI);

        UriBuilder builder = new UriBuilder(provider.RequestUserAuthorization(authorizationState));
        NameValueCollection queryParameters = HttpUtility.ParseQueryString(builder.Query);

        queryParameters.Set("access_type", "offline");
        queryParameters.Set("approval_prompt", "force");
        queryParameters.Set("user_id", emailAddress);
        queryParameters.Set("state", state);

        builder.Query = queryParameters.ToString();
        return builder.Uri.ToString();
    }
示例#8
0
        private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
        {
            // Get the auth URL:
            IAuthorizationState state = new AuthorizationState(new[] { DriveService.Scopes.Drive.GetStringValue() });
            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);

            Uri authUri = arg.RequestUserAuthorization(state);

            // Request authorization from the user (by opening a browser window):
            Process.Start(authUri.ToString());
            Console.Write("  Authorization Code: ");
            string authCode = Console.ReadLine();
            Console.WriteLine();

            // Retrieve the access token by using the authorization code:
            var result = arg.ProcessUserAuthorization(authCode, state);

            Console.WriteLine("RefreshToken: {0}", state.RefreshToken);
            System.IO.File.WriteAllText("refreshtoken.txt", state.RefreshToken);

            return result;
        }
示例#9
0
        private static IAuthorizationState AuthProvider(NativeApplicationClient argTokenProvider)
        {
            try
            {
                IAuthorizationState state = new AuthorizationState(new[] { AnalyticsService.Scopes.Analytics.GetStringValue() });
                state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);

                string refreshToken = LoadRefreshToken();
                if (!String.IsNullOrEmpty(refreshToken))
                {
                    state.RefreshToken = refreshToken;

                    if (argTokenProvider.RefreshToken(state, null))
                        return state;
                }

                Uri authUri = argTokenProvider.RequestUserAuthorization(state);

                Process.Start(authUri.ToString());
                Console.Write(" authorization Code: ");
                string authCode = Console.ReadLine(); //4/pBCEKiIoAJCjvZSgKaEw03eO0gdk.ctpr2xLkGjoVgrKXntQAax0QqPmbcwI
                Console.WriteLine();

                // Retrieve the access token by using the authorization code:
                var result = argTokenProvider.ProcessUserAuthorization(authCode, state);

                StoreRefreshToken(result);

                return result;

            }
            catch (Exception ex)
            {
                throw;
            }
        }
示例#10
0
        private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
        {
            IAuthorizationState state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() });
            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);

            string path = "auth.txt";
            if (File.Exists(path))
            {

                state.RefreshToken = File.ReadAllText(path);
                arg.RefreshToken(state);
                //state = arg.ProcessUserAuthorization(state.AccessToken, state);
            }
            else
            {

                Uri authUri = arg.RequestUserAuthorization(state);

                // Request authorization from the user (by opening a browser window):
                Process.Start(authUri.ToString());
                Console.Write("  Authorization Code: ");
                string authCode = string.Empty;
                int count = 0;
                while (string.IsNullOrEmpty(authCode) && count < 500)
                {
                    foreach (Process proc in Process.GetProcesses())
                    {
                        if (proc.MainWindowTitle.StartsWith("Success code="))
                        {
                            authCode = proc.MainWindowTitle.Split('=').Last().Split(' ').First();
                        }
                    }
                    Thread.Sleep(50);
                    Application.DoEvents();
                    count++;
                }
                Console.WriteLine();
                // Retrieve the access token by using the authorization code:
                state = arg.ProcessUserAuthorization(authCode, state);
            }

            File.WriteAllText(path, state.RefreshToken);

            return state;
        }
示例#11
0
        private IAuthorizationState getAuthentication(NativeApplicationClient arg)
        {
            log.Debug("Authenticating with Google calendar service...");
            // Get the auth URLs:
            IAuthorizationState state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue(), "https://www.googleapis.com/auth/userinfo.email" });
            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            state.RefreshToken = Settings.Instance.RefreshToken;
            Uri authUri = arg.RequestUserAuthorization(state);

            IAuthorizationState result = null;

            if (state.RefreshToken == "") {
                log.Info("No refresh token available - need user authorisation.");

                // Request authorization from the user (by opening a browser window):
                Process.Start(authUri.ToString());

                frmGoogleAuthorizationCode eac = new frmGoogleAuthorizationCode();
                if (eac.ShowDialog() == DialogResult.OK) {
                    if (string.IsNullOrEmpty(eac.authcode))
                        log.Debug("User continued but did not provide a code! This isn't going to work...");
                    else
                        log.Debug("User has provided authentication code.");

                    // Retrieve the access/refresh tokens by using the authorization code:
                    result = arg.ProcessUserAuthorization(eac.authcode, state);

                    //save the refresh token for future use
                    Settings.Instance.RefreshToken = result.RefreshToken;
                    Settings.Instance.Save();
                    log.Info("Refresh and Access token successfully retrieved.");

                    getGaccountEmail(result.AccessToken, true);
                } else {
                    log.Info("User declined to provide authorisation code. Sync will not be able to work.");
                    String noAuth = "Sorry, but this application will not work if you don't give it access to your Google Calendar :(";
                    MessageBox.Show(noAuth, "Authorisation not given", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    throw new System.ApplicationException(noAuth);
                }
            } else {
                try {
                    arg.RefreshToken(state, null);
                    if (string.IsNullOrEmpty(state.AccessToken))
                        log.Error("Failed to retrieve Access token.");
                    else
                        log.Debug("Access token refreshed - expires " + ((DateTime)state.AccessTokenExpirationUtc).ToLocalTime().ToString());
                } catch (System.Exception ex) {
                    log.Error(ex.GetType().ToString() + " " + ex.Message);
                    log.Error(ex.StackTrace);
                    MainForm.Instance.Logboxout("Failed to obtain Calendar access from Google - it's possible your access has been revoked."
                        + "\r\nTry disconnecting your Google account and reauthenticating.");
                }
                result = state;
                getGaccountEmail(result.AccessToken, false);
            }
            return result;
        }
        private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
        {
            // Get the auth URL:
            IAuthorizationState state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() });
            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            Uri authUri = arg.RequestUserAuthorization(state);

            // Request authorization from the user (by opening a browser window):
            Process.Start(authUri.ToString());
            string authCode = "4/USRsNMQpLCUgsr2cv1VZM0U-cx5t.ohfarZngF4kVOl05ti8ZT3YdL5qWcwI";// Console.ReadLine();
            //Console.WriteLine();

            // Retrieve the access token by using the authorization code:
            return arg.ProcessUserAuthorization(authCode, state);
        }
示例#13
0
        private static IAuthorizationState GetAuthentication(NativeApplicationClient arg)
        {
            // Get the auth URL:
            //IAuthorizationState state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.ToString() });
            IAuthorizationState state = new AuthorizationState(new[] { "https://www.google.com/calendar/feeds" });
            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            Uri authUri = arg.RequestUserAuthorization(state);

            // Request authorization from the user (by opening a browser window):
            Process.Start(authUri.ToString());
            Console.Write("  Authorization Code: ");
            string authCode = Console.ReadLine();

            // Retrieve the access token by using the authorization code:
            return arg.ProcessUserAuthorization(authCode, state);
        }
示例#14
0
 /// <summary>
 /// OAuth验证方法
 /// </summary>
 /// <param name="arg"></param>
 /// <returns></returns>
 private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
 {
     IAuthorizationState state = new AuthorizationState(new[] { AUTHURI });
     state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
     state.AccessToken = ACCESSTOKEN;
     Uri authUri = arg.RequestUserAuthorization(state);
     return arg.ProcessUserAuthorization(authcode);
 }
        private static IAuthorizationState getAuthentication(NativeApplicationClient arg) {
            log.Debug("Authenticating with Google calendar service...");
            // Get the auth URL:
            IAuthorizationState state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() });
            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            state.RefreshToken = Settings.Instance.RefreshToken;
            Uri authUri = arg.RequestUserAuthorization(state);

            IAuthorizationState result = null;

            if (state.RefreshToken == "") {
                log.Info("No refresh token available - need user authorisation.");

                // Request authorization from the user (by opening a browser window):
                Process.Start(authUri.ToString());

                frmGoogleAuthorizationCode eac = new frmGoogleAuthorizationCode();
                if (eac.ShowDialog() == DialogResult.OK) {
                    if (string.IsNullOrEmpty(eac.authcode))
                        log.Debug("User continued but did not provide a code! This isn't going to work...");
                    else
                        log.Debug("User has provided authentication code.");

                    // Retrieve the access/refresh tokens by using the authorization code:
                    result = arg.ProcessUserAuthorization(eac.authcode, state);

                    //save the refresh token for future use
                    Settings.Instance.RefreshToken = result.RefreshToken;
                    Settings.Instance.Save();
                    log.Info("Refresh and Access token successfully retrieved.");

                    return result;
                } else {
                    log.Info("User declined to provide authorisation code. Sync will not be able to work.");
                    String noAuth = "Sorry, but this application will not work if you don't give it access to your Google Calendar :(";
                    MessageBox.Show(noAuth, "Authorisation not given", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    throw new System.ApplicationException(noAuth);
                }
            } else {
                arg.RefreshToken(state, null);
                if (string.IsNullOrEmpty(state.AccessToken))
                    log.Error("Failed to retrieve Access token.");
                else
                    log.Debug("Access token refreshed - expires " + ((DateTime)state.AccessTokenExpirationUtc).ToLocalTime().ToString());
                result = state;
                return result;
            }

        }
示例#16
0
        /// <summary>
        /// Exchange an authorization code for OAuth 2.0 credentials.
        /// </summary>
        /// <param name="authorizationCode">Authorization code to exchange for OAuth 2.0 credentials.</param>
        /// <param name="refreshToken"></param>
        /// <param name="callbackUrl"></param>
        /// <returns>OAuth 2.0 credentials.</returns>
        public static IAuthorizationState ExchangeCode([NotNull] String authorizationCode, string refreshToken,
                                                       [NotNull] string callbackUrl)
        {
            if (authorizationCode == null) throw new ArgumentNullException("authorizationCode");
            if (callbackUrl == null) throw new ArgumentNullException("callbackUrl");

            var provider = new NativeApplicationClient(
                GoogleAuthenticationServer.Description, "647667148.apps.googleusercontent.com", "SHvBqFmGtXq5bTPqY242oNvB");
            IAuthorizationState state = new AuthorizationState();
            state.Callback = new Uri(callbackUrl);
            state.RefreshToken = refreshToken;
            try
            {
                state = provider.ProcessUserAuthorization(authorizationCode, state);
                provider.RequestUserAuthorization();
                return state;
            }
            catch (ProtocolException)
            {
                throw new Exception(null);
            }
        }
示例#17
0
        private IAuthorizationState GetAuthorization(NativeApplicationClient arg)
        {
            // Get the auth URL:
            IAuthorizationState authState = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() });
            authState.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            Uri uriAuth = arg.RequestUserAuthorization(authState);

            string strAuthCode = "";

            // Request authorization from the user (by opening a browser window):
            using ( Admin.frmOAuth objOAuth = new global::CTWebMgmt.Admin.frmOAuth(uriAuth.ToString()))
            {
                Cursor.Current = Cursors.Default;
                objOAuth.ShowDialog();
                strAuthCode = objOAuth.strAuthCode;
            }

            // Retrieve the access token by using the authorization code:
            return arg.ProcessUserAuthorization(strAuthCode, authState);
        }
        private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
        {
            // Get the auth URL:
            IAuthorizationState state = new AuthorizationState(new[] { DriveService.Scopes.Drive.GetStringValue() });
            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            Uri authUri = arg.RequestUserAuthorization(state);

            // Request authorization from the user (by opening a browser window):
            Process.Start(authUri.ToString());
            AuthenticationCode authCodeForm = new AuthenticationCode();

            if (authCodeForm.ShowDialog() == DialogResult.OK)
            {
                return arg.ProcessUserAuthorization(authCodeForm.Code, state);
            }

            return null;
        }
        private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
        {
            // Get the auth URL:
            IAuthorizationState state =
                new AuthorizationState(
                    new[]
                        {
                            Google.Apis.Admin.Directory.directory_v1.DirectoryService.Scopes.AdminDirectoryUser.GetStringValue(),
                            Google.Apis.Admin.Directory.directory_v1.DirectoryService.Scopes.AdminDirectoryUserAlias.GetStringValue(),
                            Google.Apis.Admin.Directory.directory_v1.DirectoryService.Scopes.AdminDirectoryOrgunit.GetStringValue(),
                            Google.Apis.Admin.Directory.directory_v1.DirectoryService.Scopes.AdminDirectoryGroupMember.GetStringValue(),
                            Google.Apis.Admin.Directory.directory_v1.DirectoryService.Scopes.AdminDirectoryDeviceChromeos.GetStringValue(),
                            Google.Apis.Admin.Directory.directory_v1.DirectoryService.Scopes.AdminDirectoryDeviceMobile.GetStringValue(),
                            Google.Apis.Admin.Directory.directory_v1.DirectoryService.Scopes.AdminDirectoryDeviceMobileAction.GetStringValue(),
                            GroupssettingsService.Scopes.AppsGroupsSettings.GetStringValue() });

            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);

            if (!String.IsNullOrWhiteSpace(_refreshToken))
            {
                state.RefreshToken = _refreshToken;

                if (arg.RefreshToken(state))
                    return state;
            }

            var authUri = arg.RequestUserAuthorization(state);

            // Request authorization from the user (by opening a browser window):
            Process.Start(authUri.ToString());
            Console.Write("  Authorization Code: ");
            var authCode = Console.ReadLine();
            Console.WriteLine();

            // Retrieve the access token by using the authorization code:
            var result = arg.ProcessUserAuthorization(authCode, state);
            Console.WriteLine("Refresh Token: " + result.RefreshToken);

            return result;
        }
示例#20
0
        private static IAuthorizationState GetAuthentication(NativeApplicationClient arg)
        {
            // Get the auth URL:
            IAuthorizationState state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() });
            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            state.RefreshToken = Settings.Instance.RefreshToken;
            Uri authUri = arg.RequestUserAuthorization(state);

            IAuthorizationState result = null;

            if (state.RefreshToken == "")
            {
                // Request authorization from the user (by opening a browser window):
                Process.Start(authUri.ToString());

                EnterAuthorizationCode eac = new EnterAuthorizationCode();
                if (eac.ShowDialog() == DialogResult.OK)
                {
                    // Retrieve the access/refresh tokens by using the authorization code:
                    result = arg.ProcessUserAuthorization(eac.authcode, state);

                    //save the refresh token for future use
                    Settings.Instance.RefreshToken = result.RefreshToken;
                    XMLManager.export(Settings.Instance, MainForm.FILENAME);

                    return result;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                arg.RefreshToken(state, null);
                result = state;
                return result;
            }
        }
示例#21
0
文件: frmMain.cs 项目: festigf/g3
        private IAuthorizationState GetAuthorization(NativeApplicationClient arg)
        {
            // Get the auth URL:
            IAuthorizationState state = new AuthorizationState(new[] { DriveService.Scopes.Drive.GetStringValue() });
            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            IAuthorizationState result = null;
            string refreshToken = LoadRefreshToken();
            if (!String.IsNullOrEmpty(refreshToken))
            {
                state.RefreshToken = refreshToken;

                if (arg.RefreshToken(state))
                    return state;
            }
            frmAuthorizationCode ac = new frmAuthorizationCode();
            Uri authUri = arg.RequestUserAuthorization(state);

            // Request authorization from the user (by opening a browser window):
            Process.Start(authUri.ToString());

            if (ac.ShowDialog() == DialogResult.OK)
            {
                result = arg.ProcessUserAuthorization(ac.txtAC.Text, state);
                StoreRefreshToken(state);
            }
            return result;
        }