Exemple #1
0
 public IAuthorizationState GetAuthorization(Credentials credentials, string authCode)
 {
     var state = GetState();
       var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, credentials.ClientID, credentials.ClientSecret);
       provider.ProcessUserAuthorization(authCode, state);
       return state;
 }
Exemple #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 static GoogleAuthenticator GetAuthenticator(string authorizationCode)
        {
            var client = new NativeApplicationClient(GoogleAuthenticationServer.Description, _clientId, _clientSecret);
            IAuthorizationState state = new AuthorizationState() { Callback = new Uri(_redirectUri) };
            state = client.ProcessUserAuthorization(authorizationCode, state);

            var auth = new OAuth2Authenticator<NativeApplicationClient>(client, (c) => state);
            auth.LoadAccessToken();

            return new GoogleAuthenticator(auth);
        }
        /// <summary>
        /// Requests authorization on a native client by using a predefined set of authorization flows.
        /// </summary>
        /// <param name="client">The client used for authorization.</param>
        /// <param name="scopes">The requested set of scopes.</param>
        /// <returns>The authorized state.</returns>
        /// <exception cref="AuthenticationException">Thrown if the request was cancelled by the user.</exception>
        public static IAuthorizationState RequestNativeAuthorization(NativeApplicationClient client,
                                                                     params string[] scopes)
        {
            IAuthorizationState state = new AuthorizationState(scopes);
            string authCode = RequestNativeAuthorization(client, state);

            if (string.IsNullOrEmpty(authCode))
            {
                throw new AuthenticationException("The authentication request was cancelled by the user.");
            }

            return client.ProcessUserAuthorization(authCode, state);
        }
Exemple #5
0
 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);
 }
Exemple #6
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;
        }
Exemple #7
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;
            }
        }
Exemple #8
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>
 /// <returns>OAuth 2.0 credentials.</returns>
 /// <exception cref="CodeExchangeException">An error occurred.</exception>
 static IAuthorizationState ExchangeCode(String authorizationCode)
 {
     var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET);
     IAuthorizationState state = new AuthorizationState();
     state.Callback = new Uri(REDIRECT_URI);
     try
     {
         state = provider.ProcessUserAuthorization(authorizationCode, state);
         return state;
     }
     catch (ProtocolException)
     {
         throw new CodeExchangeException(null);
     }
 }
        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;
        }
        /// <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);
            }
        }
        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);
        }
Exemple #12
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);
        }
Exemple #13
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;
            }

        }
Exemple #15
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 IAuthorizationState GetAuthorization(NativeApplicationClient arg)
 {
     return arg.ProcessUserAuthorization(authCode, state);
 }
        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;
        }
        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)
        {
            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;
        }
        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;
            }
        }
Exemple #21
0
        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;
        }