Beispiel #1
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));
        }
        /// <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);
            }
        }
Beispiel #3
0
        private IAuthorizationState getAuthorisation(NativeApplicationClient client)
        {
            IAuthorizationState state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() });

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

            string refreshToken = LoadRefreshToken();

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

                if (client.RefreshToken(state))
                {
                    return(state);
                }
            }

            if (!authRefreshOnly && authFunction != null)
            {
                Uri authUri = client.RequestUserAuthorization(state);

                string authResult = authFunction(authUri);

                var result = client.ProcessUserAuthorization(authResult, state);
                StoreRefreshToken(state);
                return(result);
            }
            else
            {
                return(null);
            }
        }
Beispiel #4
0
 string GetAuthorizationCodeFromUser(NativeApplicationClient arg, IAuthorizationState state)
 {
     ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe", arg.RequestUserAuthorization(state).ToString());
     Process.Start(startInfo);
     Console.WriteLine("Please login to the web page that has opened and enter the provided authorization code into the console: ");
     return Console.ReadLine();
 }
Beispiel #5
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));
        }
Beispiel #6
0
        /// <summary>
        /// 获取authcode
        /// </summary>
        public static void GetAuthCode()
        {
            InitProvider();

            IAuthorizationState state = new AuthorizationState(new[] { AUTHURI });

            state.Callback    = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            state.AccessToken = ACCESSTOKEN;
            Uri authUri = provider.RequestUserAuthorization(state);

            Process.Start(authUri.ToString());
        }
        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));
        }
        protected IAuthorizationState GetAuthorization(NativeApplicationClient arg)
        {
            authenticationFailed = false;
            isAuthenticated      = false;
            canEnableCheckCode   = true;

            IAuthorizationState state = null;

            try
            {
                // Get the auth URL.
                state          = new AuthorizationState(new[] { reactionScope });
                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());

                eventAuthorizationCodeEnter.WaitOne();

                // Retrieve the access token by using the authorization code.
                return(arg.ProcessUserAuthorization(authorizationCode, state));
            }
            catch (Exception ex)
            {
                authenticationFailed = true;

                Logger.Write(ex);
                return(null);
            }
            finally
            {
                if (authenticationFailed)
                {
                    isAuthenticated = false;
                }
                else
                {
                    isAuthenticated = true;

                    if (state != null)
                    {
                        RefreshToken = state.RefreshToken;
                    }
                }

                // The user needs to authenticate again in order to get another code.
                canEnableCheckCode = false;
                eventWaitAuthorization.Set();
            }
        }
        public static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
        {
            IAuthorizationState state = new AuthorizationState(
                new[] {
                CalendarService.Scopes.Calendar.GetStringValue()
            }
                );

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

            string refreshToken = LoadRefreshToken();

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

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

            Uri authUri = arg.RequestUserAuthorization(state);

            Process.Start(authUri.ToString());
            string authCode = "";

            AuthenticationForm authenticationDialog = new AuthenticationForm();

            authenticationDialog.ShowDialog();

            if (authenticationDialog.DialogResult.HasValue && authenticationDialog.DialogResult.Value)
            {
                authCode = authenticationDialog.authToken.Text;

                if (authCode == String.Empty)
                {
                    Application.Current.Shutdown();
                }
            }

            authenticationDialog.Hide();

            var result = arg.ProcessUserAuthorization(authCode, state);

            StoreRefreshToken(state);

            return(result);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            // clicked to initiate authentication process
            // provider and state are declared above as private static

            provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
            provider.ClientIdentifier = "<my id>.apps.googleusercontent.com";
            provider.ClientSecret     = "<my secret>";
            // next line changes if you want to access something other than Calendar
            state          = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() });
            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            Uri authUri = provider.RequestUserAuthorization(state);

            Process.Start(authUri.ToString());
        }
Beispiel #11
0
        private IAuthorizationState GetAuthentication(NativeApplicationClient arg)
        {
            try
            {
                if (state != null)
                {
                    return(state);
                }
                if (isTask)
                {
                    //  state = new AuthorizationState(new[] { "https://www.google.com/Tasks/feeds" });
                    state = new AuthorizationState(new[] { "https://www.googleapis.com/auth/tasks" });
                }
                else
                {
                    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):

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

                if (state != null && (!string.IsNullOrEmpty(state.AccessToken) || !string.IsNullOrEmpty(state.RefreshToken)))
                {
                    // Store and return the credentials.
                    if (isTask)
                    {
                        Save(true, state.RefreshToken, false);
                    }
                    else if (isContact)
                    {
                        Save(false, state.RefreshToken, true);
                    }
                    else
                    {
                        Save(false, state.RefreshToken, false);
                    }
                }
            }
            catch (Exception eX)
            {
                msg.Append(eX.Message);
            }
            return(state);
        }
Beispiel #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));
        }
Beispiel #13
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));
        }
        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());
        }
        /// <summary>
        /// gets authorization from google drive
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
        {
            if (XmlDataLayer.GetConfigEntry("authentication") == "done" &&
                System.IO.File.Exists(XmlDataLayer.GetUserApplicationDirectory() + "\\credentials"))
            {
                TaskCompletionSource <SelfAuthorizationState> tcs = new TaskCompletionSource <SelfAuthorizationState>();


                string filePath = XmlDataLayer.GetUserApplicationDirectory() + "\\credentials";

                var obj = System.IO.File.ReadAllText(filePath);
                tcs.SetResult(NewtonsoftJsonSerializer.Instance.Deserialize <SelfAuthorizationState>(obj));

                SelfAuthorizationState k = tcs.Task.Result;

                return(k);
            }
            else
            {
                // 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());

                Thread response = new Thread(GetResponse);
                response.SetApartmentState(ApartmentState.STA);
                response.IsBackground = true;
                response.Start();
                while (verificationEntered != true)
                {
                    Thread.Sleep(200);
                }
                string authCode = verificationString;

                // Retrieve the access token by using the authorization code:
                IAuthorizationState s = arg.ProcessUserAuthorization(authCode, state);
                var serialized        = NewtonsoftJsonSerializer.Instance.Serialize(s);
                System.IO.File.WriteAllText(XmlDataLayer.GetUserApplicationDirectory() + "\\credentials", serialized);
                return(s);
            }
        }
Beispiel #16
0
        private 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):
            GoogleLogin gl = new GoogleLogin(authUri);

            gl.ShowDialog();
            String[] tokens   = gl.m_authorizationCode.Split('=');
            String   authCode = tokens[1];

            // Retrieve the access token by using the authorization code:
            return(arg.ProcessUserAuthorization(authCode, state));
        }
Beispiel #17
0
        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);

            //Process.Start(authUri.ToString());
            //Console.Write("  Authorization Code: ");
            //string authCode = Console.ReadLine();
            //Console.WriteLine();

            var authCode = "4/dEI9atO-L397j9RoVvEeVDMflTnE.clwK8izsHyIZOl05ti8ZT3bpoi5teQI";

            // Retrieve the access token by using the authorization code:
            return(arg.ProcessUserAuthorization(authCode, state));
        }
Beispiel #18
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 = ClientCredentials.CLIENT_ID;

            IAuthorizationState authorizationState = new AuthorizationState(ClientCredentials.SCOPES);
            authorizationState.Callback = new Uri(ClientCredentials.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();
        }
Beispiel #19
0
        private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
        {
            string authocode = null;

            // 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());
            InputBox.Show("Authorization Code", "Enter Authorization Code", ref authocode);
            string authCode = authocode;

            accesstoken = authocode;
            // Retrieve the access token by using the authorization code:
            return(arg.ProcessUserAuthorization(authCode, state));
        }
Beispiel #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);
            }
        }
Beispiel #21
0
        private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
        {
            // Get the auth URL:
            IAuthorizationState state = new AuthorizationState(
                new[] { WindowsLiveClient.Scopes.Basic });

            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();

            //var authCode = BrowserForm.GetToken(authUri.ToString());

            // Retrieve the access token by using the authorization code:
            return(arg.ProcessUserAuthorization(authCode ?? string.Empty, state));
        }