예제 #1
0
        public virtual async Task <IOAuth1Account> AuthenticateAsync(IOAuth1Options options)
        {
            // Set the current expected redirect uri
            oauth = new OAuth1(options);

            var url = await oauth.GetInitialUrlAsync();

            var svc = new SFSafariViewController(NSUrl.FromString(url.AbsoluteUri))
            {
                Delegate = new NativeSFSafariViewControllerDelegate
                {
                    DidFinishHandler = (obj) =>
                    {
                        tcsAuth.TrySetResult(default(IOAuth1Account));
                    }
                }
            };

            tcsAuth = new TaskCompletionSource <IOAuth1Account>();


            await Plugin.SocialAuth.iOS.SocialAuth.PresentingViewController.PresentViewControllerAsync(svc, true);


            return(await tcsAuth.Task);
        }
예제 #2
0
 protected override string GetAuthorizationHeader()
 {
     return(OAuth1.GetAuthorizationHeader(
                Method,
                Url,
                new Dictionary <string, string> (Parameters),
                this.consumerKey,
                this.consumerSecret,
                string.Empty,
                string.Empty));
 }
예제 #3
0
        public bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
        {
            if (oauth == null || oauth.CallbackUrl == null)
            {
                return(false);
            }

            // Make sure we're redirecting from our SFSafariViewController and not some other app
            if (sourceApplication != "com.apple.SafariViewService")
            {
                return(false);
            }

            var uri = new Uri(url.AbsoluteString);

            // Only handle schemes we expect
            if (!WebUtil.CanHandleCallback(oauth.CallbackUrl, uri))
            {
                return(false);
            }

            var resp = oauth.ParseCallback(uri);

            var waitReq = new System.Threading.ManualResetEventSlim();

            IDictionary <string, string> items = null;

            var accessTokenTask = Task.Run(async() =>
            {
                items = await oauth.GetAccessTokenAsync(resp);
            });

            accessTokenTask.Wait();

            var account = oauth.GetAccountFromResponse <OAuth1Account>(items);

            Plugin.SocialAuth.iOS.SocialAuth.PresentingViewController.InvokeOnMainThread(async() =>
                                                                                         await Plugin.SocialAuth.iOS.SocialAuth.PresentingViewController.DismissViewControllerAsync(true));

            if (account == null)
            {
                tcsAuth?.TrySetException(new Exception("Failed to parse server response."));
            }
            else
            {
                tcsAuth?.TrySetResult(account);
            }

            // Reset oauth for next request
            oauth = null;

            return(true);
        }
예제 #4
0
        public override Task <Response> GetResponseAsync(CancellationToken cancellationToken)
        {
            //
            // Make sure we have an account
            //
            if (Account == null)
            {
                throw new InvalidOperationException("You must specify an Account for this request to proceed");
            }

            //
            // Sign the request before getting the response
            //
            var req = GetPreparedWebRequest();

            //
            // Make sure that the parameters array contains
            // mulitpart keys if we're dealing with a buggy
            // OAuth implementation (I'm looking at you Flickr).
            //
            // These normally shouldn't be included: http://tools.ietf.org/html/rfc5849#section-3.4.1.3.1
            //
            var ps = new Dictionary <string, string> (Parameters);

            if (includeMultipartsInSignature)
            {
                foreach (var p in Multiparts)
                {
                    if (!string.IsNullOrEmpty(p.TextData))
                    {
                        ps[p.Name] = p.TextData;
                    }
                }
            }

            //
            // Authorize it
            //
            var authorization = OAuth1.GetAuthorizationHeader(
                Method,
                Url,
                ps,
                Account.Properties["oauth_consumer_key"],
                Account.Properties["oauth_consumer_secret"],
                Account.Properties["oauth_token"],
                Account.Properties["oauth_token_secret"]);

            req.Headers[HttpRequestHeader.Authorization] = authorization;

            return(base.GetResponseAsync(cancellationToken));
        }
        public virtual async Task <IOAuth1Account> AuthenticateAsync(IOAuth1Options options)
        {
            // Set the current expected redirect uri
            oauth = new OAuth1(options);

            var url = await oauth.GetInitialUrlAsync();

            tcsAuth = new TaskCompletionSource <IOAuth1Account>();

            // DO TABS
            authSession = new CustomTabsAuthSession();
            authSession.AuthTaskCompletionSource = new TaskCompletionSource <IOAuth1Account>();

            authSession.ParentActivity            = Plugin.SocialAuth.Droid.SocialAuth.CurrentActivity;
            authSession.CustomTabsActivityManager = new CustomTabsActivityManager(authSession.ParentActivity);
            authSession.CustomTabsActivityManager.NavigationEvent += (navigationEvent, extras) =>
            {
                if (navigationEvent == CustomTabsCallback.TabHidden)
                {
                    if (authSession.AuthTaskCompletionSource != null)
                    {
                        authSession.AuthTaskCompletionSource.TrySetCanceled();
                    }
                }
            };

            authSession.CustomTabsActivityManager.CustomTabsServiceConnected += delegate
            {
                var ctam = authSession.CustomTabsActivityManager;
                var ses  = ctam.Session;

                var builder = new CustomTabsIntent.Builder(ses)
                              .SetShowTitle(true);

                var customTabsIntent = builder.Build();
                customTabsIntent.Intent.AddFlags(Android.Content.ActivityFlags.SingleTop | ActivityFlags.NoHistory | ActivityFlags.NewTask);

                CustomTabsHelper.AddKeepAliveExtra(authSession.ParentActivity, customTabsIntent.Intent);

                customTabsIntent.LaunchUrl(authSession.ParentActivity, Android.Net.Uri.Parse(url.AbsoluteUri));
            };

            if (!authSession.CustomTabsActivityManager.BindService())
            {
                tcsAuth.TrySetException(new Exception("CustomTabs not supported."));
            }

            return(await tcsAuth.Task);
        }
예제 #6
0
        public void GetBaseString()
        {
            var baseString = OAuth1.GetBaseString(
                "GET",
                new Uri("http://www.flickr.com/services/oauth/request_token"),
                new Dictionary <string, string> ()
            {
                { "oauth_nonce", "89601180" },
                { "oauth_timestamp", "1305583298" },
                { "oauth_consumer_key", "653e7a6ecc1d528c516cc8f92cf98611" },
                { "oauth_signature_method", "HMAC-SHA1" },
                { "oauth_version", "1.0" },
                { "oauth_callback", "http://www.example.com" },
            });

            Assert.That(
                baseString,
                Is.EqualTo("GET&http%3A%2F%2Fwww.flickr.com%2Fservices%2Foauth%2Frequest_token&oauth_callback%3Dhttp%253A%252F%252Fwww.example.com%26oauth_consumer_key%3D653e7a6ecc1d528c516cc8f92cf98611%26oauth_nonce%3D89601180%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1305583298%26oauth_version%3D1.0"));
        }
        public bool Callback(Intent intent, Bundle state)
        {
            if (authSession == null || intent == null)
            {
                return(false);
            }

            var uri = new Uri(intent.Data.ToString());

            // Only handle schemes we expect
            if (!WebUtil.CanHandleCallback(oauth.CallbackUrl, uri))
            {
                return(false);
            }

            var resp = oauth.ParseCallback(uri);

            IDictionary <string, string> items = null;

            var accessTokenTask = Task.Run(async() =>
            {
                items = await oauth.GetAccessTokenAsync(resp);
            });

            accessTokenTask.Wait();

            var account = oauth.GetAccountFromResponse <OAuth1Account>(items);

            if (account == null)
            {
                tcsAuth?.TrySetException(new Exception("Failed to parse server response."));
            }
            else
            {
                tcsAuth?.TrySetResult(account);
            }

            oauth       = null;
            authSession = null;

            return(true);
        }
예제 #8
0
        public void GetSignature()
        {
            var sig = OAuth1.GetSignature(
                "GET",
                new Uri("http://www.flickr.com/services/oauth/request_token"),
                new Dictionary <string, string> ()
            {
                { "oauth_nonce", "95613465" },
                { "oauth_timestamp", "1305586162" },
                { "oauth_consumer_key", "653e7a6ecc1d528c516cc8f92cf98611" },
                { "oauth_signature_method", "HMAC-SHA1" },
                { "oauth_version", "1.0" },
                { "oauth_callback", "http://www.example.com" },
            },
                "34bf6099d244db6a",
                "");

            Assert.That(
                sig,
                Is.EqualTo("gICkK2bXRMKVYCvwX8bGsC/QbKY="));
        }
예제 #9
0
        /// <summary>
        /// Gets OAuth authorization header.
        /// </summary>
        /// <remarks>
        /// <para>
        /// Make sure that the parameters array contains mulitpart keys if we're dealing with a buggy
        /// OAuth implementation (such as Flickr).
        /// </para>
        /// <para>
        /// These normally shouldn't be included: http://tools.ietf.org/html/rfc5849#section-3.4.1.3.1
        /// </para>
        /// </remarks>
        protected virtual string GetAuthorizationHeader()
        {
            var ps = new Dictionary <string, string>(Parameters);

            if (includeMultipartsInSignature)
            {
                foreach (var p in Multiparts)
                {
                    if (!string.IsNullOrEmpty(p.TextData))
                    {
                        ps[p.Name] = p.TextData;
                    }
                }
            }

            return(OAuth1.GetAuthorizationHeader(
                       Method,
                       Url,
                       ps,
                       Account.Properties["oauth_consumer_key"],
                       Account.Properties["oauth_consumer_secret"],
                       Account.Properties["oauth_token"],
                       Account.Properties["oauth_token_secret"]));
        }
예제 #10
0
 void Awake()
 {
     m_authority = new OAuth1(kPrefix, kConsumerKey, kConsumerSecret);
     Dispatcher <float> .AddListener(MeshPattern.kOnExportUpdate, StlExportUpdate);
 }
예제 #11
0
    public IEnumerator UploadModel(string title, string tags, bool isPublic, bool canDownload)
    {
        if (!m_stlReady)
        {
            m_cancelling = false;
            Dispatcher <string, string, PanelController.Handler, PanelController.Handler> .Broadcast(
                PanelController.kEventShowProgress,
                OAuth1.kOnUpdateProgress, "Processing ({0:0%} completed)...",
                delegate() {},
                delegate() { m_cancelling = true; Scheduler.StopCoroutines(m_pattern); }
                );

            while (!m_cancelling && !m_stlReady)
            {
                Dispatcher <float> .Broadcast(OAuth1.kOnUpdateProgress, m_pattern.loadProgress);

                yield return(null);
            }
            if (m_cancelling)
            {
                yield break;
            }
            Dispatcher <float> .Broadcast(OAuth1.kOnUpdateProgress, 1.0f);
        }

        Dispatcher <string, string, PanelController.Handler, PanelController.Handler> .Broadcast(
            PanelController.kEventShowProgress,
            OAuth1.kOnUpdateProgress, "Uploading ({0:0%} completed)...",
            delegate() {},
            delegate() { m_cancelling = true; Scheduler.StopCoroutines(this); }
            );

        byte[] fileData       = m_stlStream.ToArray();
        string fileBase64Data = System.Convert.ToBase64String(fileData);

        title = title.Replace(" ", "").Trim();
        string fileName = title;

        if (string.IsNullOrEmpty(fileName))
        {
            fileName = "Untitled.stl";
            title    = "Untitled";
        }
        else if (!fileName.Contains("."))
        {
            fileName = fileName + ".stl";
        }

        Json payload = new Json();

        payload.Add("file", OAuth1.UrlEncode(fileBase64Data));
        payload.Add("fileName", fileName);
        payload.Add("uploadScale", VoxelBlob.kVoxelSizeInMm * 0.001f);
        payload.Add("hasRightsToModel", 1);
        payload.Add("acceptTermsAndConditions", 1);
        payload.Add("title", title);
        payload.Add("isPublic", isPublic ? 1 : 0);
        payload.Add("isDownloadable", canDownload ? 1 : 0);
        payload.Add("tags", tags.Split(',', ';'));

        yield return(Scheduler.StartCoroutine(m_authority.PostData("http://api.shapeways.com/models/v1",
                                                                   payload, OnSuccess, OnFailure), this));

        m_stlStream.Close();
    }
예제 #12
0
        Task GetAccessTokenAsync()
        {
            #if DEBUG
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"OAuth1Authenticator.GetAccessTokenAsync ");
            sb.AppendLine($"        token = {token}");
            System.Diagnostics.Debug.WriteLine(sb.ToString());
            #endif

            RequestParameters = new Dictionary <string, string>
            {
                { "oauth_token", token }
            };

            if (verifier != null)
            {
                RequestParameters["oauth_verifier"] = verifier;
                System.Diagnostics.Debug.WriteLine($"        verifier = {verifier}");
            }

            // WebRequest Replaced with HttpRequest for .net Standard 1.1
            HttpWebRequest req = OAuth1.CreateRequest
                                 (
                "GET",
                accessTokenUrl,
                request_parameters,
                consumerKey,
                consumerSecret,
                tokenSecret
                                 );

            if (this.HttpWebClientFrameworkType == HttpWebClientFrameworkType.WebRequest)
            {
                WebResponse response = req.GetResponseAsync().Result;

                return(req.GetResponseAsync().ContinueWith
                       (
                           respTask =>
                {
                    var content = respTask.Result.GetResponseText();

                    var accountProperties = WebEx.FormDecode(content);

                    accountProperties["oauth_consumer_key"] = consumerKey;
                    accountProperties["oauth_consumer_secret"] = consumerSecret;

                    if (getUsernameAsync != null)
                    {
                        getUsernameAsync(accountProperties).ContinueWith(uTask =>
                        {
                            if (uTask.IsFaulted)
                            {
                                OnError(uTask.Exception);
                            }
                            else
                            {
                                OnSucceeded(uTask.Result, accountProperties);
                            }
                        });
                    }
                    else
                    {
                        OnSucceeded("", accountProperties);
                    }
                }
                       ));
            }
            else if (this.HttpWebClientFrameworkType == HttpWebClientFrameworkType.HttpClient)
            {
                throw new NotImplementedException("HttpClient implementation!");
            }

            return(null);
        }
예제 #13
0
        /// <summary>
        /// Method that returns the initial URL to be displayed in the web browser.
        /// </summary>
        /// <returns>
        /// A task that will return the initial URL.
        /// </returns>
        public override Task <Uri> GetInitialUrlAsync(Dictionary <string, string> query_parameters = null)
        {
            /*
             *  mc++
             *  OriginalString property of the Uri object should be used instead of AbsoluteUri
             *
             *  otherwise trailing slash is added.
             *
             *  string[] uris = new string[]
             *  {
             *      "http://xamarin.com/",
             *      "http://xamarin.com",
             *  };
             *  foreach (string u in uris)
             *  {
             *      uri = new Uri(u);
             *      Console.WriteLine("uri.AbsoluteUri = " + uri.AbsoluteUri);
             *      Console.WriteLine("uri.OriginalString = " + uri.OriginalString);
             *  }
             *
             *  The problem is whether to send original string to be compared with registered
             *  redirect_url on the authorization server od "correct" url (AblsoluteUrl) with
             *  slash
             */
            //string oauth_callback_uri_absolute = callbackUrl.AbsoluteUri;
            string oauth_callback_uri_original = callbackUrl.OriginalString;

            //System.Diagnostics.Debug.WriteLine("GetInitialUrlAsync callbackUrl.AbsoluteUri    = " + oauth_callback_uri_absolute);
            System.Diagnostics.Debug.WriteLine("GetInitialUrlAsync callbackUrl.OriginalString = " + oauth_callback_uri_original);

            string oauth_callback_uri = oauth_callback_uri_original;

            var req = OAuth1.CreateRequest
                      (
                "GET",
                requestTokenUrl,
                new Dictionary <string, string>()
            {
                { "oauth_callback", oauth_callback_uri },
            },
                consumerKey,
                consumerSecret,
                ""
                      );

            if (this.HttpWebClientFrameworkType == HttpWebClientFrameworkType.WebRequest)
            {
                return(req.GetResponseAsync()
                       .ContinueWith
                       (
                           respTask =>
                {
                    var content = respTask.Result.GetResponseText();

                    var r = WebEx.FormDecode(content);

                    token = r["oauth_token"];
                    tokenSecret = r["oauth_token_secret"];

                    string paramType = authorizeUrl.AbsoluteUri.IndexOf("?") >= 0 ? "&" : "?";

                    var url = authorizeUrl.AbsoluteUri + paramType + "oauth_token=" + Uri.EscapeDataString(token);
                    return new Uri(url);
                }
                       ));
            }
            else if (this.HttpWebClientFrameworkType == HttpWebClientFrameworkType.HttpClient)
            {
                throw new NotImplementedException("HttpClient implementation!");
            }

            return(null);
        }