예제 #1
0
        ///<summary>Called by Open Dental Proper to get the real access code form the code given by Dropbox.  Returns empty string if something went wrong.</summary>
        public static string GetDropboxAccessToken(string code, string appkey, string appsecret)
        {
            string ret = "";
            ApplicationException ae   = null;
            ManualResetEvent     wait = new ManualResetEvent(false);

            new Task(async() => {
                try {
                    OAuth2Response resp = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code, appkey, appsecret);
                    if (string.IsNullOrEmpty(resp.AccessToken))
                    {
                        throw new Exception("Empty token returned by Dropbox.");
                    }
                    ret = resp.AccessToken;
                }
                catch (Exception ex) {
                    ae = new ApplicationException(ex.Message, ex);
                }
                wait.Set();
            }).Start();
            wait.WaitOne(10000);
            if (ae != null)
            {
                throw ae;
            }
            return(ret);
        }
예제 #2
0
 public void GetAuthTokens(Uri uri)
 {
     if (uri != null)
     {
         if (!uri.ToString().StartsWith(_redirectUri, StringComparison.OrdinalIgnoreCase))
         {
             // we need to ignore all navigation that isn't to the redirect uri.
             TestMessage = "Waiting for user details...";
             return;
         }
         Testing = false;
         if (!uri.ToString().Equals(_redirectUri, StringComparison.OrdinalIgnoreCase))
         {
             OAuth2Response result = null;
             try
             {
                 result = DropboxOAuth2Helper.ParseTokenFragment(uri);
             }
             catch (ArgumentException e)
             {
                 Dev2Logger.Warn(e.Message, "Warewolf Warn");
             }
             AuthenticationFailed(uri, result);
         }
     }
 }
예제 #3
0
        private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            if (!e.Url.AbsoluteUri.ToString().StartsWith(redirectURI.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            try {
                OAuth2Response response = DropboxOAuth2Helper.ParseTokenFragment(e.Url);

                if (response.State != DropBoxOAuth2State)
                {
                    return;
                }

                this.AccessToken = response.AccessToken;
                this.Uid         = response.Uid;
                this.Result      = true;

                appClosing = true;
            } catch (ArgumentException ae) {
            } finally {
                //e.Cancel = true;
                this.Close();
            }
        }
        private void WebBrowser_OnNavigating(object sender, NavigatingCancelEventArgs e)
        {
            if (!e.Uri.ToString().StartsWith(RedirectUri, StringComparison.OrdinalIgnoreCase))
            {
                // we need to ignore all navigation that isn't to the redirect uri.
                return;
            }

            try
            {
                OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(e.Uri);
                if (result.State != this.oauth2State)
                {
                    // The state in the response doesn't match the state in the request.
                    return;
                }

                this.AccessToken = result.AccessToken;
                this.Uid         = result.Uid;
            }
            catch (ArgumentException)
            {
                // There was an error in the URI passed to ParseTokenFragment
            }
            finally
            {
                e.Cancel = true;
                this.Close();
            }
        }
        private void BrowserNavigating(object sender, NavigatingCancelEventArgs e)
        {
            // Shamelessly taken from this example: https://github.com/dropbox/dropbox-sdk-dotnet/blob/master/dropbox-sdk-dotnet/Examples/SimpleTest/LoginForm.xaml.cs
            if (!e.Uri.ToString().StartsWith(redirectUri.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                // we need to ignore all navigation that isn't to the redirect uri.
                haveResult = true;
                return;
            }

            try
            {
                OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(e.Uri);
                if (result.State != oAuth2State)
                {
                    // The state in the response doesn't match the state in the request.
                    haveResult = true;
                    return;
                }

                accessToken = result.AccessToken;
            }
            catch (ArgumentException)
            {
                // There was an error in the URI passed to ParseTokenFragment
            }
            finally
            {
                e.Cancel = true;
            }

            haveResult = true;
            Close();
        }
예제 #6
0
        void AuthenticationFailed(Uri uri, OAuth2Response result)
        {
            if (result != null)
            {
                if (result.State != _oauth2State)
                {
                    TestPassed       = false;
                    TestFailed       = true;
                    TestMessage      = "Authentication failed";
                    AccessToken      = string.Empty;
                    HasAuthenticated = false;
                }
                else
                {
                    TestPassed       = true;
                    TestFailed       = false;
                    TestMessage      = "";
                    AccessToken      = result.AccessToken;
                    HasAuthenticated = true;
                }
            }
            else
            {
                TestPassed       = false;
                TestFailed       = true;
                TestMessage      = "Authentication failed";
                AccessToken      = string.Empty;
                HasAuthenticated = false;

                var errorDescription = HttpUtility.ParseQueryString(uri.ToString()).Get("error_description");

                TestMessage = errorDescription ?? "Authentication failed";
            }
        }
예제 #7
0
        private void Browser_Navigating(object sender, System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            if (!e.Uri.AbsoluteUri.ToString().StartsWith(RedirectUri.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                // we need to ignore all navigation that isn't to the redirect uri.
                return;
            }


            try
            {
                OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(e.Uri);
                if (result.State != DBoauth2State)
                {
                    return;
                }

                this.AccessToken = result.AccessToken;
                this.Uid         = result.Uid;
                this.Result      = true;
            }
            catch (ArgumentException ex)
            {
                MessageBox.Show(ex.Message);
            }

            finally
            {
                e.Cancel = true;
                this.Close();
            }
        }
예제 #8
0
        public async Task <AuthorizationTokenDTO> Authenticate(ExternalAuthenticationDTO externalAuthDTO)
        {
            string code  = GetTokenValueByKey(externalAuthDTO.RequestQueryString, "code");
            string state = GetTokenValueByKey(externalAuthDTO.RequestQueryString, "state");

            OAuth2Response response = await GetAuthToken(code);

            if (response == null)
            {
                throw new ArgumentNullException("Unable to get authentication token in dropbox.");
            }

            string externalId = "";

            using (var dbx = new DropboxClient(response.AccessToken))
            {
                externalId = (await dbx.Users.GetCurrentAccountAsync()).Email;
            }

            return(new AuthorizationTokenDTO()
            {
                Token = response.AccessToken,
                ExternalStateToken = state,
                ExternalAccountId = externalId
            });
        }
예제 #9
0
        public static async Task <string> GetUserAuthorisationCode(string userAccessCode, AuthorisationSettings authSettings)
        {
            var message = "";

            try
            {
                OAuth2Response response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(userAccessCode,
                                                                                         authSettings.DropboxAppKey,
                                                                                         authSettings.DropboxSecretKey,
                                                                                         authSettings.DropboxRedirectURI.ToString());

                if (response != null)
                {
                    //if (response.State != null && response.State.Equals(authSettings.SecurityToken))
                    //{
                    return(response.AccessToken);
                    //}
                }
                else
                {
                    message = "Failed: Access code is not secure.";
                }
            }
            catch (ArgumentException ex)
            {
                message = "Failed: " + ex.Message;
            }

            return(message);
        }
예제 #10
0
        public void GetAuthTokens(Uri uri)
        {
            if (uri != null)
            {
                if (!uri.ToString().StartsWith(_redirectUri, StringComparison.OrdinalIgnoreCase))
                {
                    // we need to ignore all navigation that isn't to the redirect uri.
                    TestMessage = "Waiting for user details...";
                    return;
                }
                Testing = false;
                if (!uri.ToString().Equals(_redirectUri, StringComparison.OrdinalIgnoreCase))
                {
                    OAuth2Response result = null;
                    try
                    {
                        result = DropboxOAuth2Helper.ParseTokenFragment(uri);
                    }
                    catch (ArgumentException)
                    {
                    }

                    if (result != null)
                    {
                        if (result.State != _oauth2State)
                        {
                            TestPassed       = false;
                            TestFailed       = true;
                            TestMessage      = "Authentication failed";
                            AccessToken      = string.Empty;
                            HasAuthenticated = false;
                        }
                        else
                        {
                            TestPassed       = true;
                            TestFailed       = false;
                            TestMessage      = "";
                            AccessToken      = result.AccessToken;
                            HasAuthenticated = true;
                        }
                    }
                    else
                    {
                        TestPassed       = false;
                        TestFailed       = true;
                        TestMessage      = "Authentication failed";
                        AccessToken      = string.Empty;
                        HasAuthenticated = false;

                        string errorDescription = HttpUtility.ParseQueryString(uri.ToString()).Get("error_description");

                        TestMessage = errorDescription ?? "Authentication failed";
                    }
                }
            }
        }
        public void IdTokenParsingNoPasswordClaimsTest()
        {
            TokenResponse tr = this.CreateTokenResponse();

            tr.IdToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiI5MDgzY2NiOC04YTQ2LTQzZTctODQzOS0xZDY5NmRmOTg0YWUiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC8zMGJhYTY2Ni04ZGY4LTQ4ZTctOTdlNi03N2NmZDA5OTU5NjMvIiwiaWF0IjoxNDAwNTQxMzk1LCJuYmYiOjE0MDA1NDEzOTUsImV4cCI6MTQwMDU0NTU5NSwidmVyIjoiMS4wIiwidGlkIjoiMzBiYWE2NjYtOGRmOC00OGU3LTk3ZTYtNzdjZmQwOTk1OTYzIiwib2lkIjoiNGY4NTk5ODktYTJmZi00MTFlLTkwNDgtYzMyMjI0N2FjNjJjIiwidXBuIjoiYWRtaW5AYWFsdGVzdHMub25taWNyb3NvZnQuY29tIiwidW5pcXVlX25hbWUiOiJhZG1pbkBhYWx0ZXN0cy5vbm1pY3Jvc29mdC5jb20iLCJzdWIiOiJCczVxVG4xQ3YtNC10VXIxTGxBb3pOS1NRd0Fjbm4ydHcyQjlmelduNlpJIiwiZmFtaWx5X25hbWUiOiJBZG1pbiIsImdpdmVuX25hbWUiOiJBREFMVGVzdHMifQ.";
            AuthenticationResult result = OAuth2Response.ParseTokenResponse(tr, null);

            Verify.IsNull(result.UserInfo.PasswordChangeUrl);
            Verify.IsNull(result.UserInfo.PasswordExpiresOn);
        }
예제 #12
0
        private void WebBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (!e.Uri.IsLoopback)
            {
                return;
            }

            Response = DropboxOAuth2Helper.ParseTokenFragment(e.Uri);

            DialogResult = true;
            Close();
        }
예제 #13
0
        /// <summary>
        /// Validates the login attempt
        /// If successful the AccessToken is populated
        /// </summary>
        /// <param name="uri">The URL the login attempt navigated to</param>
        /// <returns>True if login successful</returns>
        internal bool Validate(Uri uri)
        {
            AccessToken = "";

            OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(uri);

            if (result.State == _Oauth2State)
            {
                AccessToken = result.AccessToken;
                return(true);
            }

            return(false);
        }
    public static async Task <OAuth2Response> ValidateAccessCode(string code)
    {
        try
        {
            OAuth2Response response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code, _AppKey, _AppSecret);

            return(response);
        }
        catch (OAuth2Exception e)
        {
            Debug.Log(e.Message);
            return(null);
        }
    }
예제 #15
0
        private void webBrowser_Navigating(object sender, System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            try
            {
                this.Result = false;

                #region Dropbox

                if (AuthType == AuthenticateTypeList.Dropbox)
                {
                    if (!e.Uri.ToString().StartsWith(db_RedirectUri, StringComparison.OrdinalIgnoreCase))
                    {
                        return;
                    }

                    OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(e.Uri);
                    if (result.State != this.db_Oauth2State)
                    {
                        return;
                    }

                    this.db_AccessToken = result.AccessToken;
                    this.db_UserId      = result.Uid;
                    this.Result         = true;

                    var httpClient = new HttpClient()
                    {
                        Timeout = TimeSpan.FromMinutes(20)
                    };

                    var config = new DropboxClientConfig("SimpleTestApp")
                    {
                        HttpClient = httpClient
                    };

                    db_Client = new DropboxClient(this.db_AccessToken, config);

                    this.Close();
                }

                #endregion Dropbox
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                this.Result = false;
                this.Close();
            }
        }
예제 #16
0
        public bool FinishFromUri(Uri uri)
        {
            try
            {
                string   url = uri.ToString();
                string[] param = url.Substring(url.IndexOf('?') + 1).Split('&');
                string   state, code;
                if (param[0].StartsWith("state"))
                {
                    state = param[0].Substring(param[0].IndexOf('=') + 1);
                    code  = param[1].Substring(param[1].IndexOf('=') + 1);
                }
                else
                {
                    code  = param[0].Substring(param[0].IndexOf('=') + 1);
                    state = param[1].Substring(param[1].IndexOf('=') + 1);
                }

                if (state != oauth2State)
                {
                    return(false);
                }

                HttpClientHandler handler = new HttpClientHandler();
                if (Arg.ProxyState != 0)
                {
                    handler.Proxy = new System.Net.WebProxy(Arg.ProxyHost, Arg.ProxyPort);
                }
                OAuth2Response result = DropboxOAuth2Helper.ProcessCodeFlowAsync(code, App_key, App_secret, RedirectUri, new HttpClient(handler)).Result;

                this.AccessToken = result.AccessToken;
                Arg.AccessToken  = result.AccessToken;
                this.Uid         = result.Uid;

                DropboxClientConfig config = new DropboxClientConfig("ConfDoctor");
                config.HttpClient = new HttpClient(handler);
                client            = new DropboxClient(AccessToken, config);

                FullAccount account = client.Users.GetCurrentAccountAsync().Result;
                Arg.UserName = account.Name.DisplayName;

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
예제 #17
0
        public async void ProcessCodeFlow(string appKey, string appSecret, Action <string> onSuccess,
                                          Action <Exception> onFailure)
        {
            //continue code flow
            try
            {
                OAuth2Response result = await DropboxOAuth2Helper.ProcessCodeFlowAsync(AccessToken, appKey, appSecret);

                AccessToken = result.AccessToken;
                onSuccess(AccessToken);
            }
            catch (Exception e)
            {
                onFailure(e);
            }
        }
        private const string AppSecret = "2a3si3j0kvgrush"; // <- not that secret in that case

        /// <summary>
        /// Initializes the Dropbox library, and ignites the authorization process if needed.
        /// </summary>
        /// <returns>Returns a task to be awaited until the initialization process is done.</returns>
        public async Task Initialize()
        {
            string accessToken;

            config = ConfigurationUtility.ReadConfigurationFile(GetType());

            if (config.TryGetValue("AccessToken", out accessToken) && string.IsNullOrWhiteSpace(accessToken) == false)
            {
                accessToken = SecurityUtility.UnprotectString(accessToken, DataProtectionScope.CurrentUser);
            }

            if (string.IsNullOrWhiteSpace(accessToken))
            {
                Uri authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(AppKey, false);
                var url          = authorizeUri.ToString();

                MessageBox.Show("After you click the OK button on this dialog, a web page asking you to allow the application will open, and then another one containing a code.\r\n\r\nOnce you see the code, please copy it to the clipboard by selecting it and pressing Ctrl+C, or right click and 'Copy' menu.", "Authorization", MessageBoxButton.OK, MessageBoxImage.Information);
                Process.Start(url);
                MessageBox.Show("Please proceed by closing this dialog once you copied the code.", "Authorization", MessageBoxButton.OK, MessageBoxImage.Information);

                string code = null;

                try
                {
                    code = Clipboard.GetText();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("An error occured:\r\n" + ex.Message, "Authorization Failed", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                OAuth2Response response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code, AppKey, AppSecret);

                accessToken = response.AccessToken;

                ConfigurationUtility.CreateConfigurationFile(GetType(), new Dictionary <string, string>
                {
                    { "AccessToken", SecurityUtility.ProtectString(accessToken, DataProtectionScope.CurrentUser) },
                });

                MessageBox.Show("Authorization process succeeded.", "Authorization", MessageBoxButton.OK, MessageBoxImage.Information);
            }

            dropboxClient = new DropboxClient(accessToken);
        }
        public void GetAccessToken(DropboxLoginSuccessfulMessage msg)
        {
            try
            {
                OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(msg.RedirectUri);
                if (result.State != _oauth2State)
                {
                    throw new Exception("OAuth2 state mismatch");
                }

                _settings.Token = result.AccessToken;
                Messenger.Default.Send(new CredentialsUpdatedMessage());
            }
            catch (Exception ex)
            {
                Messenger.Default.Send(new AuthenticationErrorMessage(ex));
            }
        }
예제 #20
0
        async private void NextBtn_Click(object sender, EventArgs e)
        {
            if (StorageList.SelectedIndices.Count > 0)
            {
                if (StorageList.SelectedIndices[0].Equals(0))
                {
                    if (!IsDropboxEnable)
                    {
                        Process.Start(DropboxOAuth2Helper.GetAuthorizeUri("jj2eyo41xn837y7", false).ToString()); //вызов страницы для подтверждения доступа и получения кода
                        CodeConfirmForm LetMeConfirm = new CodeConfirmForm();
                        LetMeConfirm.ShowDialog();
                        OAuth2Response resp = await DropboxOAuth2Helper.ProcessCodeFlowAsync(LetMeConfirm.CodeConfirm, "jj2eyo41xn837y7", "ldfel2pg0e7yery", null, null);

                        DropboxCode = resp.AccessToken;
                        LetMeConfirm.Close();
                        SQLiteConnection    db = new SQLiteConnection(DataBasePath);
                        List <StorageClass> DataStorageImport = new List <StorageClass>();
                        DataStorageImport = db.Query <StorageClass>("SELECT * FROM StorageKeys WHERE UserId='" + UserId + "'");
                        if (DataStorageImport.Count > 0)
                        {
                            DataStorageImport = db.Query <StorageClass>("UPDATE StorageKeys SET DropboxKey='" + DropboxCode + "'" + "WHERE UserId='" + UserId + "'");
                        }
                        else
                        {
                            StorageClass RegUserInfo = new StorageClass()
                            {
                                Id      = UserId,
                                DropBox = DropboxCode
                            };
                            db.Insert(RegUserInfo);
                        }
                        IsDropboxEnable = true;
                    }
                    //using (DropboxClient dbx = new DropboxClient(DropboxCode))
                    //{
                    //    var full = await dbx.Users.GetCurrentAccountAsync();
                    //    MessageBox.Show("Username: "******"\n E-mail: " + full.Email);
                    //}
                    WorkDirectioryForm WorkDirectory = new WorkDirectioryForm();
                    WorkDirectory.Show();
                    this.Hide();
                }
            }
        }
예제 #21
0
        private async Task <OAuth2Response> GetAuthToken(string code)
        {
            OAuth2Response response = null;

            try
            {
                response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(
                    code,
                    dropboxAuthAppKey,
                    dropboxAuthAppSecret,
                    RedirectURI);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex.InnerException);
            }

            return(response);
        }
예제 #22
0
        private async Task <OAuth2Response> HandleJSRedirect()
        {
            var context = await http.GetContextAsync();

            // We only care about request to TokenRedirectUri endpoint.
            while (context.Request.Url.AbsolutePath != JSRedirectUri.AbsolutePath)
            {
                context = await http.GetContextAsync();
            }

            String redirectUri = new Uri(context.Request.QueryString["url_with_fragment"]).ToString();

            //retrieve code from redirectUri
            int            index    = redirectUri.IndexOf("code=");
            String         code     = redirectUri.Substring(index + 5);
            OAuth2Response response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code, _appKey, _appSecret, RedirectUri.ToString());

            return(response);
        }
예제 #23
0
        public async Task <AuthorizationResult> AuthenticateAsync(Uri authorizationUri, Uri redirectUri, CallState callState)
        {
            string key = authorizationUri.AbsoluteUri + redirectUri.AbsoluteUri;

            if (IOMap.ContainsKey(key))
            {
                string value = IOMap[key];
                if (value[0] == 'P')
                {
                    return(OAuth2Response.ParseAuthorizeResponse(value.Substring(1), callState));
                }

                if (value[0] == 'A')
                {
                    string [] segments = value.Substring(1).Split(new [] { Delimiter }, StringSplitOptions.RemoveEmptyEntries);
                    return(new AuthorizationResult(error: segments[0], errorDescription: segments[1]));
                }
            }

            return(null);
        }
        public void Authenticate(Uri authorizationUri, Uri redirectUri, IDictionary <string, object> headersMap, CallState callState)
        {
            string key = authorizationUri.AbsoluteUri + redirectUri.AbsoluteUri;

            LastAuthorizationResult = null;
            if (IOMap.ContainsKey(key))
            {
                string value = IOMap[key];
                if (value[0] == 'P')
                {
                    LastAuthorizationResult = OAuth2Response.ParseAuthorizeResponse(value.Substring(1), callState);
                }
                else if (value[0] == 'A')
                {
                    string[] segments = value.Substring(1).Split(new[] { Delimiter }, StringSplitOptions.RemoveEmptyEntries);
                    LastAuthorizationResult = new AuthorizationResult(error: segments[0], errorDescription: segments[1]);
                }
            }

            LastHeadersMap = headersMap;
        }
예제 #25
0
파일: Form1.cs 프로젝트: Nero-X/DropBoxAPI
 private void W_LoadError(object sender, CefSharp.LoadErrorEventArgs e)
 {
     if (e.FailedUrl.StartsWith(RedirectUri, StringComparison.InvariantCultureIgnoreCase))
     {
         try
         {
             OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(new Uri(e.FailedUrl));
             if (result.State == oauth2State)
             {
                 w.Invoke((MethodInvoker)(() => w.Hide()));
                 Properties.Settings.Default.AccessToken = result.AccessToken;
                 Properties.Settings.Default.Save();
                 Invoke((MethodInvoker)(() => InitClient(result.AccessToken)));
             }
         }
         catch (ArgumentException)
         {
             MessageBox.Show("There was an error");
         }
     }
 }
        public OAuth2Response Deserialize(Stream jsonStream)
        {
            if (jsonStream == null)
            {
                throw new ArgumentNullException("jsonStream");
            }

            var graph    = (GoogleGraph)jsonSerializer.ReadObject(jsonStream);
            var response = new OAuth2Response
            {
                UserId        = Get(graph.Id),
                Name          = Get(graph.Name),
                FirstName     = Get(graph.FirstName),
                LastName      = Get(graph.LastName),
                Email         = Get(graph.Email),
                EmailVerified = bool.Parse(Get(graph.Verified)),
                Url           = Get(graph.Link)
            };

            return(response);
        }
        private void BrowserNavigating(object sender, NavigatingCancelEventArgs e)
        {
            if (!e.Uri.ToString().StartsWith(RedirectUri, StringComparison.OrdinalIgnoreCase))
            {
                // we need to ignore all navigation that isn't to the redirect uri.
                return;
            }

            try
            {
                OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(e.Uri);
                if (result.State != this.oauth2State)
                {
                    return;
                }

                this.AccessToken             = result.AccessToken;
                this.Uid                     = result.Uid;
                this.Result                  = true;
                Settings.Default.AccessToken = AccessToken;
                Settings.Default.Uid         = Uid;
                Settings.Default.Save();
                var task = Task.Run((Func <Task>)LoginForm.Run);
                task.Wait();
                var task2 = Task.Run((Func <Task>)HomePage.Run);
                task2.Wait();
                this.RefreshEvent(this, new EventArgs());
            }
            catch (ArgumentException ers)
            {
                // There was an error in the URI passed to ParseTokenFragment
                MessageBox.Show("リンクに問題が発生しました。\n\n" + ers.Message.Replace("Invalid OAuth 2.0 response, missing access_token and/or uid.", "無効なOAuth 2.0レスポンスです。access_tokenまたはuidがありません。\nリクエストを許可してください。"), "DropBoxリンク", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                e.Cancel = true;
                this.Close();
            }
        }
        public OAuth2Response Deserialize(Stream jsonStream)
        {
            if (jsonStream == null)
            {
                throw new ArgumentNullException("jsonStream");
            }

            var graph = serializer.Deserialize <WindowsLiveGraph>(new StreamReader(jsonStream).ReadToEnd());

            var response = new OAuth2Response
            {
                UserId        = Get(graph.Id),
                Name          = Get(graph.Name),
                FirstName     = Get(graph.FirstName),
                LastName      = Get(graph.LastName),
                Email         = Get(graph.Emails["preferred"] ?? graph.Emails["account"]),
                EmailVerified = bool.Parse(Get(graph.Verified)),
                Url           = Get(graph.Link)
            };

            return(response);
        }
예제 #29
0
    //public async void CodeInputChnagedAsync(Text tex)
    //{
    //    if (string.IsNullOrEmpty(tex.text))
    //        return;
    //    OAuth2Response response = await cmd_Dropbox.ValidateAccessCode(tex.text);
    //    if (response != null)
    //    {
    //        MessageBox.Show("Success", "Authenticated successfully.\n\nYou can now start using Asset Cat", () =>
    //        {
    //            PlayerPrefs.SetString("Token", AvoEx.AesEncryptor.Encrypt(response.AccessToken));
    //            PlayerPrefs.Save();
    //            SceneManager.LoadSceneAsync("02_DataLoad");
    //        });
    //    }
    //    else
    //    {
    //        MessageBox.Show("Error", tex.text + "\n\nFailed To Authenticate\n\nEnter code again or get new code", () => { });
    //    }
    //}

    public async void VerifyTokenAsync(InputField tex)
    {
        if (string.IsNullOrEmpty(tex.text))
        {
            return;
        }
        OAuth2Response response = await cmd_Dropbox.ValidateAccessCode(tex.text);

        if (response != null)
        {
            MessageBox.Show("Success", "Authenticated successfully.\n\nYou can now start using Asset Cat", () =>
            {
                PlayerPrefs.SetString("Token", AvoEx.AesEncryptor.Encrypt(response.AccessToken));
                PlayerPrefs.Save();
                SceneManager.LoadSceneAsync("02_DataLoad");
            });
        }
        else
        {
            MessageBox.Show("Error", tex.text + "\n\nFailed To Authenticate\n\nEnter code again or get new code", () => { });
        }
    }
예제 #30
0
        /// <summary>
        /// Asynchronously checks the provider authentication code.
        /// </summary>
        /// <param name="code">The code.</param>
        protected override async Task <SerializableAPIResult <SerializableAPICredentials> > CheckProviderAuthCodeAsync(
            string code)
        {
            if (m_result == null)
            {
                m_result = new SerializableAPIResult <SerializableAPICredentials>();
            }

            try
            {
                OAuth2Response response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code,
                                                                                         Util.Decrypt(DropboxCloudStorageServiceSettings.Default.AppKey,
                                                                                                      CultureConstants.InvariantCulture.NativeName),
                                                                                         Util.Decrypt(DropboxCloudStorageServiceSettings.Default.AppSecret,
                                                                                                      CultureConstants.InvariantCulture.NativeName)).ConfigureAwait(false);

                await CheckAuthenticationAsync().ConfigureAwait(false);

                if (!m_result.HasError)
                {
                    DropboxCloudStorageServiceSettings.Default.AccessToken = response.AccessToken;
                }
            }
            catch (OAuth2Exception exc)
            {
                m_result.Error = new SerializableAPIError {
                    ErrorMessage = exc.Message
                };
            }
            catch (Exception exc)
            {
                m_result.Error = new SerializableAPIError {
                    ErrorMessage = exc.Message
                };
            }

            return(m_result);
        }