示例#1
0
        /// <summary>
        /// Completes the Windows 8 Metro Twitter Login experience and returns the OAuth tokens.
        /// </summary>
        /// <param name="consumerKey"></param>
        /// <param name="consumerSecret"></param>
        /// <returns>The logged in users OAuth Tokens</returns>
        public static async Task <OAuthTokenResponse> WebAuthenticationAsync(string consumerKey, string consumerSecret)
        {
            const string replyurl = "http://reply_here/";

            var requestToken = await RequestTokenAsync(consumerKey, consumerSecret, replyurl);

            var authuri = BuildAuthorizationUri(requestToken.Token, false);

            WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                WebAuthenticationOptions.None,
                authuri,
                new Uri(replyurl));

            if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
            {
                var accesstoken = WebAuthenticationResult.ResponseData.ToString();
                var verifier    = ParseQuerystringParameter("oauth_verifier", accesstoken);

                return(await AccessTokenAsync(consumerKey, consumerSecret, requestToken.Token, verifier));
            }
            else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
            {
                return(new OAuthTokenResponse()
                {
                    Error = WebAuthenticationResult.ResponseErrorDetail.ToString()
                });
            }
            else
            {
                return(new OAuthTokenResponse()
                {
                    Error = WebAuthenticationResult.ResponseStatus.ToString()
                });
            }
        }
示例#2
0
        /// <summary>
        /// Starts the authentication operation with a given settings.
        /// </summary>
        /// <param name="authSettings">Authorization settings</param>
        /// <param name="silentMode">Tells the web authentication broker to not render any UI.</param>
        /// <exception cref="InTouchException">Thrown when a HTTP error occurred or inner exceptions were caught.</exception>
        /// <returns></returns>
        public async Task Authorize(AuthorizationSettings authSettings = null, bool silentMode = false)
        {
            var ad = authSettings ?? new AuthorizationSettings();

            if (ClientId == 0)
            {
                throw new NullReferenceException("ClientId cannot be null or empty");
            }

            var authParams = new Dictionary <string, object>
            {
                { "client_id", ClientId },
                { "v", APIVersion },
                { "scope", (int)ad.Scope },
                { "display", ToEnumString(ad.Display) },
                { "response_type", "token" },
                { "revoke", ad.Revoke ? 1 : 0 },
                { "redirect_uri", ad.RedirectUri },
                { "lang", "en" }
            };

            var authUrl = new Uri($"{AuthUrl}?{authParams.GetQueryString()}");
            var endUrl  = new Uri($"{ad.RedirectUri}#access_token=");
            var wao     = silentMode ? WebAuthenticationOptions.SilentMode : WebAuthenticationOptions.None;

            try
            {
                WebAuthenticationResult webAuthResult;

                if (ad.SSOEnabled)
                {
                    webAuthResult = await WebAuthenticationBroker.AuthenticateAsync(wao, authUrl);
                }
                else
                {
                    webAuthResult = await WebAuthenticationBroker.AuthenticateAsync(wao, authUrl, endUrl);
                }

                if (webAuthResult.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    var responseData =
                        ParseQueryString(webAuthResult.ResponseData.Substring(ad.RedirectUri.ToString().Length + 1));

                    SetSessionData(responseData["access_token"], int.Parse(responseData["user_id"]),
                                   int.Parse(responseData["expires_in"]));
                }
                else if (webAuthResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                {
                    throw new InTouchException("A HTTP error occurred while attempting to contact the server.", webAuthResult.ResponseErrorDetail);
                }
                else
                {
                    throw new InTouchException("An error occurred while attempting to authorize.", webAuthResult.ResponseStatus);
                }
            }
            catch (Exception ex)
            {
                throw new InTouchException("An exception has occurred while authenticating.", ex);
            }
        }
示例#3
0
        /// <summary>
        /// Authentication process
        /// </summary>
        /// <param name="requestUri"> Request Uri</param>
        /// <param name="callbackUri"> Uri result</param>
        /// <returns> Returns login status</returns>
        public async Task <AuthenticationResult> Authenticate(Uri requestUri, Uri callbackUri)
        {
            WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(
                WebAuthenticationOptions.None,
                requestUri,
                callbackUri);

            switch (result.ResponseStatus)
            {
            case WebAuthenticationStatus.Success:
                return(new AuthenticationResult {
                    ResponseData = result.ResponseData, ResponseStatus = AuthenticationResultStatus.Success
                });

            case WebAuthenticationStatus.UserCancel:
                return(new AuthenticationResult {
                    ResponseData = result.ResponseData, ResponseStatus = AuthenticationResultStatus.UserCancel, ResponseErrorDetail = result.ResponseErrorDetail
                });

            case WebAuthenticationStatus.ErrorHttp:
                return(new AuthenticationResult {
                    ResponseData = result.ResponseData, ResponseStatus = AuthenticationResultStatus.ErrorHttp, ResponseErrorDetail = result.ResponseErrorDetail
                });

            default:
                // TODO: Change with correct name;
                throw new ArgumentException("error");
            }
        }
示例#4
0
        public async Task <AccessInformation> AuthRequestAsync()
        {
            var callbackUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString().Replace("ms-app://", "https://imacode.ninja/");
            var state       = Guid.NewGuid();

            var requestUri = $"{TokenRequestUrl}?client_id={ClientId}&scope={AuthorizationScopes.ReadWriteSkills} {AuthorizationScopes.ReadModels} {AuthorizationScopes.TestingSkills} &response_type=code&state={state:N}&redirect_uri={callbackUri}";
            var result     = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, new Uri(requestUri, UriKind.Absolute), new Uri(callbackUri, UriKind.Absolute));

            var queryParams = HttpUtility.ParseQueryString(new Uri(result.ResponseData).Query);

            if (result.ResponseStatus != WebAuthenticationStatus.Success || state.ToString("N") != queryParams["state"])
            {
                return(null);
            }

            var authCode = queryParams["code"];

            var dictionary = GetCodeDetails("authorization_code", "code", authCode);


            var authResponse = await new HttpClient().PostAsync(AccessRequestUrl, new FormUrlEncodedContent(dictionary));

            if (!authResponse.IsSuccessStatusCode)
            {
                return(null);
            }

            using (var json = new JsonTextReader(new StreamReader(await authResponse.Content.ReadAsStreamAsync())))
            {
                return(Serializer.Deserialize <AccessInformation>(json));
            }
        }
示例#5
0
        private async Task <string> GetAuthorizeCodeAsync()
        {
            Uri uri = new Uri("https://api.weibo.com/oauth2/authorize");

            List <KeyValuePair <string, string> > pairs = new List <KeyValuePair <string, string> >();

            pairs.Add(new KeyValuePair <string, string>("client_id", appInfo.Key));
            pairs.Add(new KeyValuePair <string, string>("redirect_uri", appInfo.RedirectUri));
            pairs.Add(new KeyValuePair <string, string>("display", Untils.GetDisplay()));

            uri = Untils.AddHeader(uri, pairs);

            WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, uri, new Uri(appInfo.RedirectUri));

            string code = "";

            switch (result.ResponseStatus)
            {
            case WebAuthenticationStatus.Success:
                code = new Uri(result.ResponseData).GetQueryParameter("code");
                break;

            case WebAuthenticationStatus.UserCancel:
                throw new Exception("user cancel authorize");

            case WebAuthenticationStatus.ErrorHttp:
                throw new Exception("http connection error");

            default:
                throw new Exception("unknow error");
            }
            return(code);
        }
示例#6
0
        private async Task <string> GetAuthorizationCodeAsync(string returnUrl = null)
        {
            var requestUri = new Uri(this.GetAuthorizationCodeRequestUrl(returnUrl));

            var result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, requestUri, new Uri(this.returnUrl));

            IDictionary <string, string> authenticationResponseValues = null;

            if (result != null && !string.IsNullOrEmpty(result.ResponseData))
            {
                authenticationResponseValues = UrlHelper.GetQueryOptions(new Uri(result.ResponseData));

                this.ThrowIfError(authenticationResponseValues);
            }
            else if (result != null && result.ResponseStatus == WebAuthenticationStatus.UserCancel)
            {
                throw new ServiceException(new Error {
                    Code = GraphErrorCode.AuthenticationCancelled.ToString()
                });
            }

            string code;

            if (authenticationResponseValues != null && authenticationResponseValues.TryGetValue("code", out code))
            {
                return(code);
            }

            return(null);
        }
示例#7
0
        public async Task <bool?> LoginAsync(string oauthKey, string oauthSecret)
        {
#if NETFX_CORE
            // Create Auth url
            var    state    = Guid.NewGuid();
            string startUrl = $"https://www.tvshowtime.com/oauth/authorize?state={state}&redirect_uri={AuthHelper.RedirectUrl}&client_id={oauthKey}";
            var    startUri = new Uri(startUrl);
            var    endUri   = new Uri(AuthHelper.RedirectUrl);

            try
            {
                // Launch authentication webview
                var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, endUri);

                Token = await AuthHelper.RetrieveToken(webAuthenticationResult, oauthKey, oauthSecret);

                return(!string.IsNullOrWhiteSpace(Token));
            }
            catch
            {
                return(null);
            }
#else
            throw new NotImplementedException();
#endif
        }
        /// <summary>
        /// Gets the user realm through navigation.
        /// </summary>
        private async void NavigationButton_Click(object sender, RoutedEventArgs e)
        {
            // Build the /FirstSignIn URL.
            var firstSignInUri = new Uri(
                string.Format("{0}/discovery{1}/me/FirstSignIn?redirect_uri={2}&scope={3}",
                              this.DiscoveryServiceHost.Text,
#if DISCOVERY_API_V1
                              "/v1.0",
#else
                              string.Empty,
#endif
                              TerminalUriText,
                              Scope));
            var terminalUri = new Uri(TerminalUriText);

            var webAuthResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, firstSignInUri, terminalUri)
                                .AsTask().ConfigureAwait(continueOnCapturedContext: true);

            if (webAuthResult.ResponseStatus == WebAuthenticationStatus.Success)
            {
                ParseNavigationResult(webAuthResult.ResponseData);
                RenderUserRealmData();
                this.Status.Foreground = SuccessBrush;

                // TODO: In order to use this app to get an OAuth token for another service,
                // set the Resource ID of the desired service.
                m_settings["discovery_resource"] = "https://api.office.com/discovery/";
            }
            else
            {
                // This error wasn't expected.
                this.Status.Text       = string.Format("Error = {0}\nHTTP code = {1}\n", webAuthResult.ResponseStatus, webAuthResult.ResponseErrorDetail);
                this.Status.Foreground = ErrorBrush;
            }
        }
        private async Task <string> AuthenticateFacebookAsync()
        {
            try
            {
                var fb = new FacebookClient();

                var redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString();

                var loginUri = fb.GetLoginUrl(new
                {
                    client_id     = AppId,
                    redirect_uri  = redirectUri,
                    scope         = ExtendedPermissions,
                    display       = "popup",
                    response_type = "token"
                });

                var callbackUri = new Uri(redirectUri, UriKind.Absolute);

                var authenticationResult =
                    await
                    WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None,
                                                              loginUri, callbackUri);

                return(ParseAuthenticationResult(fb, authenticationResult));
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
示例#10
0
        async Task <string> Authorize()
        {
            var guid       = System.Guid.NewGuid();
            var builder    = new UriBuilder("https://www.reddit.com/api/v1/authorize.compact");
            var httpParams = System.Web.HttpUtility.ParseQueryString(builder.Query);

            httpParams["client_id"]     = mClientId;
            httpParams["response_type"] = "code";
            httpParams["state"]         = guid.ToString();
            httpParams["redirect_uri"]  = mRedirectUrl;
            httpParams["duration"]      = "permanent";
            httpParams["scope"]         = "*";
            builder.Query = httpParams.ToString();

            var result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, builder.Uri, new Uri(mRedirectUrl));

            if (result.ResponseStatus != WebAuthenticationStatus.Success)
            {
                return(string.Empty);
            }

            var resultParams = System.Web.HttpUtility.ParseQueryString(new Uri(result.ResponseData).Query);

            // TODO varify state value also

            return(resultParams.Get("code"));
        }
示例#11
0
        public async Task <string> InvokeAsync(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                throw new ArgumentException("Missing url", nameof(url));
            }

            WebAuthenticationResult result;

            try
            {
                result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, new Uri(url));
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }

            if (result.ResponseStatus == WebAuthenticationStatus.Success)
            {
                return(result.ResponseData);
            }
            else if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
            {
                return(result.ResponseErrorDetail.ToString());
            }
            else if (result.ResponseStatus == WebAuthenticationStatus.UserCancel)
            {
                return("User cancelled");
            }
            else
            {
                return("Invalid response from WebAuthenticationBroker");
            }
        }
示例#12
0
        public async void Authorization()
        {
            Uri StartUri = new Uri(RequestParameters.api_url);
            Uri EndUri   = new Uri(RequestParameters.redirect_uri);

            WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                WebAuthenticationOptions.None,
                StartUri,
                EndUri);

            if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
            {
                RequestParameters.code = WebAuthenticationResult.ResponseData.ToString();
                RequestParameters.code = RequestParameters.code.Substring(RequestParameters.code.IndexOf("code"));
            }
            else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
            {
            }
            else
            {
            }

            HttpClient httpClient = new HttpClient();

            HttpRequestMessage  request  = new HttpRequestMessage(HttpMethod.Post, token_uri);
            HttpResponseMessage response = await httpClient.SendAsync(request);

            string responeData = await response.Content.ReadAsStringAsync();
        }
示例#13
0
        private async Task GoogleLogin()
        {
            try
            {
                WebAuthenticationResult result =
                    await WebAuthenticationBroker.AuthenticateAsync(
                        WebAuthenticationOptions.UseTitle,
                        new Uri(LoginUrl),
                        new Uri("https://accounts.google.com/o/oauth2/approval?"));

                switch (result.ResponseStatus)
                {
                case WebAuthenticationStatus.Success:
                    await TokenAuth(result.ResponseData.ToString().Split('=')[1]);

                    break;

                case WebAuthenticationStatus.UserCancel:
                case WebAuthenticationStatus.ErrorHttp:
                    break;
                }
            }
            catch (Exception e)
            {
            }
        }
示例#14
0
        public async Task <string> AuthorizeWithVimeo()
        {
            var clientId = "b8e1bff5d5d1f2c90f61017b135960adb42f5fe2";

            var SpotifyUrl = "https://api.vimeo.com/oauth/authorize?client_id=" + Uri.EscapeDataString(clientId) + "&response_type=code&redirect_uri=" + Uri.EscapeDataString("https://example/callback") + "&state=xyzbc";
            var StartUri   = new Uri(SpotifyUrl);
            var EndUri     = new Uri("https://example/callback");

            WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, StartUri, EndUri);

            if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
            {
                var responseData = WebAuthenticationResult.ResponseData;

                //await GetSpotifyUserNameAsync(WebAuthenticationResult.ResponseData.ToString());
                return(responseData);
            }
            else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
            {
                return($"HTTP Error returned by AuthenticateAsync() : {WebAuthenticationResult.ResponseErrorDetail.ToString()}");
            }
            else
            {
                return($"Error returned by AuthenticateAsync() : {WebAuthenticationResult.ResponseStatus.ToString()}");
            }
        }
示例#15
0
        private async static void PerformGoogleOAuth()
        {
            var startUri = new Uri(string.Format(login_url, formatLoginURL()));
            Uri EndUri   = new Uri("https://accounts.google.com/o/oauth2/approval?");

            try
            {
                WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.UseTitle, startUri, EndUri);

                if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    PerformTokenAuth(WebAuthenticationResult.ResponseData.ToString().Split('=')[1]);
                }
                else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                {
                    NotificationHelper.ErrorMessage("The result returned Error " + WebAuthenticationResult.ResponseErrorDetail.ToString(), "Authentication Failure");
                }
                else
                {
                    NotificationHelper.ErrorMessage("An unknown error has occurred", "Authentication Failed");
                }
            }


            catch (Exception Error)
            {
                NotificationHelper.ErrorMessage(Error.Message, "Authentication Failed");
            }
        }
示例#16
0
        /// <summary>
        /// Gets the user realm through navigation.
        /// </summary>
        private async void NavigationButton_Click(object sender, RoutedEventArgs e)
        {
            // Build the /FirstSignIn URL
            var firstSignInUri = new Uri(
                string.Format("{0}/discovery/me/FirstSignIn?redirect_uri={1}&scope={2}",
                              this.DiscoveryServiceHost.Text,
                              TerminalUriText,
                              Scope));
            var terminalUri = new Uri(TerminalUriText);

            var webAuthResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, firstSignInUri, terminalUri)
                                .AsTask().ConfigureAwait(continueOnCapturedContext: true);

            if (webAuthResult.ResponseStatus == WebAuthenticationStatus.Success)
            {
                ParseNavigationResult(webAuthResult.ResponseData);
                RenderUserRealmData();
                this.Status.Foreground = SuccessBrush;


                m_settings["discovery_resource"] = "Microsoft.SharePoint"; // TODO: for Mail, use "https://sdfpilot.outlook.com/";
            }
            else
            {
                // This error wasn't expected
                this.Status.Text       = string.Format("Error = {0}\nHTTP code = {1}\n", webAuthResult.ResponseStatus, webAuthResult.ResponseErrorDetail);
                this.Status.Foreground = ErrorBrush;
            }
        }
示例#17
0
 private async Task <WebAuthenticationResult> InvokeWABOnMainThreadAsync(
     Uri authorizationUri,
     Uri redirectUri,
     bool ssoMode,
     WebAuthenticationOptions options)
 {
     return(await CoreApplication.MainView.CoreWindow.Dispatcher.RunTaskAsync(
                async() =>
     {
         if (ssoMode)
         {
             return await
             WebAuthenticationBroker.AuthenticateAsync(options, authorizationUri)
             .AsTask()
             .ConfigureAwait(false);
         }
         else
         {
             return await WebAuthenticationBroker
             .AuthenticateAsync(options, authorizationUri, redirectUri)
             .AsTask()
             .ConfigureAwait(false);
         }
     })
            .ConfigureAwait(false));
 }
        public async Task <Uri> AuthorizeAsync(Uri authorizationUri, Uri redirectUri, CancellationToken cancellationToken)
        {
            var dispatcher = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher;

            var result = await dispatcher.RunDirectlyOrDispatchAsync(
                async innerCt =>
            {
                try
                {
                    return(await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, authorizationUri, redirectUri).AsTask(cancellationToken).ConfigureAwait(false));
                }
                catch (Exception e)
                {
                    throw new SpotifyAuthorizationException("An error has occurred while communicating with Spotify Accounts Service. See inner exception for details.", e);
                }
            },
                cancellationToken).ConfigureAwait(false);

            switch (result.ResponseStatus)
            {
            case WebAuthenticationStatus.Success:
                try
                {
                    return(new Uri(result.ResponseData));
                }
                catch (Exception e)
                {
                    throw new SpotifyAuthorizationException("An invalid URL string has been returned from the Spotify Accounts Service. See inner exception for details.", e);
                }

            default:
                throw new SpotifyWebAuthenticationBrokerException(result.ResponseStatus);
            }
        }
        public async Task SignInAsync(string clientId,
                                      Uri authUrl,
                                      Uri callbackUrl,
                                      Action <string> tokenCallback,
                                      Action <string> errorCallback)
        {
            var fullAuthUrl = string.Format(authUrl.OriginalString + "?client_id={0}&redirect_uri={1}&response_type=token", clientId, callbackUrl.OriginalString);

            var result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, new Uri(fullAuthUrl), callbackUrl);

            switch (result.ResponseStatus)
            {
            case WebAuthenticationStatus.Success:
                tokenCallback?.Invoke(GetAccessToken(result.ResponseData));
                break;

            case WebAuthenticationStatus.ErrorHttp:
                errorCallback?.Invoke(result.ResponseErrorDetail.ToString());
                break;

            case WebAuthenticationStatus.UserCancel:
                tokenCallback?.Invoke("");
                break;
            }
        }
        /// <summary>
        /// Logs in a <see cref="ParseUser" /> using Facebook for authentication. If a user for the
        /// given Facebook credentials does not already exist, a new user will be created.
        ///
        /// The user will be logged in through Facebook's OAuth web flow using the Windows
        /// WebAuthenticationBroker.
        /// </summary>
        /// <param name="permissions">A list of Facebook permissions to request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The user that was either logged in or created.</returns>
        public static async Task <ParseUser> LogInAsync(IEnumerable <string> permissions,
                                                        CancellationToken cancellationToken)
        {
            var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

            authProvider.Permissions         = permissions;
            authProvider.ResponseUrlOverride = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
            Action <Uri> navigate = async uri => {
                var result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None,
                                                                             uri);

                if (result.ResponseStatus != WebAuthenticationStatus.Success)
                {
                    cts.Cancel();
                }
                else
                {
                    authProvider.HandleNavigation(new Uri(result.ResponseData));
                }
            };

            authProvider.Navigate += navigate;
            try {
                return(await ParseUser.LogInWithAsync("facebook", cts.Token));
            } finally {
                authProvider.Navigate           -= navigate;
                authProvider.ResponseUrlOverride = null;
            }
        }
示例#21
0
        public async Task <IDictionary <string, string> > AuthorizeAsync(string serviceUri, string authorizeUri, string callbackUrl)
        {
            _tcs = new TaskCompletionSource <IDictionary <string, string> >();

            CoreDispatcher dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;

            if (dispatcher == null)
            {
                throw new Exception("No access to UI thread");
            }

            var requestUri  = new Uri(authorizeUri);
            var callbackUri = new Uri(callbackUrl);
            WebAuthenticationResult webAuthResult;

            await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                webAuthResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, requestUri, callbackUri);

                if (webAuthResult.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    ContinueWebAuthentication(webAuthResult);
                }
            });

            return(await _tcs.Task);
        }
        /// <summary>
        /// Links a <see cref="ParseUser" /> to a Facebook account, allowing you to use Facebook
        /// for authentication, and providing access to Facebook data for the user.
        ///
        /// The user will be logged in through Facebook's OAuth web flow using the Windows
        /// WebAuthenticationBroker.
        /// </summary>
        /// <param name="user">The user to link with Facebook.</param>
        /// <param name="permissions">A list of Facebook permissions to request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        public static async Task LinkAsync(ParseUser user,
                                           IEnumerable <string> permissions,
                                           CancellationToken cancellationToken)
        {
            var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

            authProvider.Permissions = permissions;
            Action <Uri> navigate = async uri => {
                var result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None,
                                                                             uri,
                                                                             FacebookAuthenticationProvider.ResponseUrl);

                if (result.ResponseStatus != WebAuthenticationStatus.Success)
                {
                    cts.Cancel();
                }
                else
                {
                    authProvider.HandleNavigation(new Uri(result.ResponseData));
                }
            };

            authProvider.Navigate += navigate;
            try {
                await user.LinkWithAsync("facebook", cts.Token);
            } finally {
                authProvider.Navigate -= navigate;
            }
        }
示例#23
0
        public static async void Login(string[] permissions, Action <WebAuthenticationResult, Exception> onComplete)
        {
            try
            {
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                {
                    var scope = string.Join(",", permissions);

                    var facebookRedirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri;

                    var requestUri  = new Uri(string.Format(FaceBookAuth, AppId, facebookRedirectUri, scope));
                    var callbackUri = new Uri(facebookRedirectUri);

                    var asyncOperation = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, requestUri, callbackUri);
                    if (onComplete != null)
                    {
                        var authResult = new WebAuthenticationResult();
                        if (asyncOperation != null)
                        {
                            authResult.ResponseData        = asyncOperation.ResponseData;
                            authResult.ResponseErrorDetail = asyncOperation.ResponseErrorDetail;
                            authResult.ResponseStatus      = (WebAuthenticationStatus)asyncOperation.ResponseStatus;
                        }
                        onComplete(authResult, null);
                    }
                });
            }
            catch (Exception ex)
            {
                if (onComplete != null)
                {
                    onComplete(null, ex);
                }
            }
        }
示例#24
0
        /// <summary>
        /// Authenticates a user to enable the user data APIs.
        /// </summary>
        /// <param name="client">The MixRadio client.</param>
        /// <param name="clientSecret">The client secret obtained during app registration</param>
        /// <param name="scopes">The scopes requested.</param>
        /// <param name="oauthRedirectUri">The OAuth completed URI.</param>
        /// <param name="cancellationToken">The cancellation token to cancel operation</param>
        /// <returns>
        /// An AuthResultCode value indicating the result
        /// </returns>
        /// <remarks>
        /// Sorry, this method is messy due to the platform differences!
        /// </remarks>
        public static async Task <AuthResultCode> AuthenticateUserAsync(this MusicClient client, string clientSecret, Scope scopes, string oauthRedirectUri = MusicClient.DefaultOAuthRedirectUri, CancellationToken?cancellationToken = null)
        {
            if (string.IsNullOrEmpty(oauthRedirectUri))
            {
                throw new ArgumentNullException("oauthRedirectUri", "You must supply your OAuth Redirect URI to allow user interaction");
            }

            if (string.IsNullOrEmpty(clientSecret))
            {
                throw new ArgumentNullException("clientSecret", "You must supply your app client secret obtained during app registration");
            }

            // See if we have a cached token...
            AuthResultCode cachedResult = await AuthenticateUserAsync(client, clientSecret, cancellationToken).ConfigureAwait(false);

            if (cachedResult == AuthResultCode.Success)
            {
                return(cachedResult);
            }

#if WINDOWS_PHONE_APP
            WebAuthenticationBroker.AuthenticateAndContinue(client.GetAuthenticationUri(scopes), new Uri(oauthRedirectUri));
            return(AuthResultCode.InProgress);
#elif WINDOWS_APP
            var authResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, client.GetAuthenticationUri(scopes), new Uri(oauthRedirectUri));

            return(await CompleteAuthenticateUserAsync(client, clientSecret, authResult, cancellationToken));
#endif
        }
示例#25
0
        public async Task <BrowserResult> InvokeAsync(BrowserOptions options)
        {
            if (string.IsNullOrWhiteSpace(options.StartUrl))
            {
                throw new ArgumentException("Missing StartUrl", nameof(options));
            }

            var startUri = new Uri(options.StartUrl);

            if (startUri.AbsolutePath.StartsWith("/v2/logout", StringComparison.OrdinalIgnoreCase))
            {
                return(await InvokeLogoutAsync(startUri));
            }

            try
            {
                var authOptions = ConfigureWebAuthOptions(options.DisplayMode);
                var authResult  = await WebAuthenticationBroker.AuthenticateAsync(authOptions, startUri, new Uri(options.EndUrl));

                return(CreateBrowserResult(authResult));
            }
            catch (Exception ex)
            {
                return(new BrowserResult
                {
                    ResultType = BrowserResultType.UnknownError,
                    Error = ex.ToString()
                });
            }
        }
示例#26
0
        /// <summary>
        /// Handles user logout.
        /// Does this by creating a logout URL and by opening this URL in webauthenticationbroker.
        /// Set acces token to 0;
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void FBLogout_Click(object sender, RoutedEventArgs e)
        {
            if (fbInfo.Values["token"].ToString() != "0")
            {
                string tokenValue = fbInfo.Values["token"].ToString();

                var redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString();
                //await fbClient.DeleteTaskAsync("me/permissions");
                Uri startUri    = new Uri(@"https://www.facebook.com/logout.php?next=https://facebook.com/&access_token=" + fbClient.AccessToken);
                Uri endUri      = new Uri(redirectUri, UriKind.Absolute);
                var redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString();

                Uri startUri = new Uri(@"https://www.facebook.com/logout.php?next=https://www.facebook.com/&access_token=" + fbClient.AccessToken);
                Uri endUri   = new Uri(redirectUri, UriKind.Absolute);

                await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, endUri);

                this.accessToken            = "0";
                this.fbInfo.Values["token"] = "0";
                fbProfilePic.Visibility     = Visibility.Collapsed;
            }
            else
            {
                var dialog = new MessageDialog("It seems that you're already logged out!");
                await dialog.ShowAsync();
            }
        }
示例#27
0
        static async Task <WebAuthenticatorResult> PlatformAuthenticateAsync(Uri url, Uri callbackUrl)
        {
            if (!IsUriProtocolDeclared(callbackUrl.Scheme))
            {
                throw new InvalidOperationException($"You need to declare the windows.protocol usage of the protocol/scheme `{callbackUrl.Scheme}` in your AppxManifest.xml file");
            }

            try
            {
                var r = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, url, callbackUrl);

                switch (r.ResponseStatus)
                {
                case WebAuthenticationStatus.Success:
                    // For GET requests this is a URI:
                    var resultUri = new Uri(r.ResponseData.ToString());
                    return(new WebAuthenticatorResult(resultUri));

                case WebAuthenticationStatus.UserCancel:
                    throw new TaskCanceledException();

                case WebAuthenticationStatus.ErrorHttp:
                    throw new HttpRequestException("Error: " + r.ResponseErrorDetail);

                default:
                    throw new Exception("Response: " + r.ResponseData.ToString() + "\nStatus: " + r.ResponseStatus);
                }
            }
            catch (FileNotFoundException)
            {
                throw new TaskCanceledException();
            }
        }
示例#28
0
        private async void AttemptLogin()
        {
            if (_client != null)
            {
                return;
            }
            if (apiKey == null)
            {
                return;
            }

            _client           = new FacebookClient();
            _client.AppId     = apiKey.APIKey;
            _client.AppSecret = apiKey.APISecret;

            //var scope = "public_profile, email";
            var scope = "public_profile,user_friends,email, user_about_me, user_hometown, user_location, user_photos, user_posts, user_status, user_videos, user_website";

            var redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString();
            var fb          = new FacebookClient();
            Uri loginUrl    = fb.GetLoginUrl(new
            {
                client_id     = apiKey.APIKey,
                redirect_uri  = redirectUri,
                response_type = "token",
                scope         = scope
            });

            Uri startUri = loginUrl;
            Uri endUri   = new Uri(redirectUri, UriKind.Absolute);

            WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, endUri);

            ParseAuthenticationResult(result);
        }
示例#29
0
        private async void LoginUwp()
        {
//#if DEBUG
//            LoginToken(69396347, "942c58d27b3c05c4ecc8b382b89a16eb25d6a49693eddb600707bd59251c4e60d71546709bde36fbf787f");
//            return;
//#endif

            try
            {
                var authResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None,
                                                                                 new Uri(_vkLoginService.GetOAuthUrl()), new Uri(VKLoginService.REDIRECT_URL));

                if (authResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                {
                    ShowError(authResult.ResponseErrorDetail.ToString());
                }
                else if (authResult.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    var    response = authResult.ResponseData.Split(new char[] { '#' })[1].Split(new char[] { '&' });
                    string token    = response[0].Split('=')[1];
                    int    userID   = int.Parse(response[2].Split('=')[1]);

                    LoginToken(userID, token);
                }
                else
                {
                    ShowError("access_denied");
                }
            }
            catch (Exception)
            {
                ShowError("connection_error");
            }
        }
示例#30
0
        public async override Task Login()
        {
            try
            {
                String FacebookURL = "https://www.facebook.com/dialog/oauth?client_id=" + Uri.EscapeDataString(ClientId) +
                                     "&redirect_uri=" + Uri.EscapeDataString(CallbackUrl) + "&scope=read_stream&display=popup&response_type=token";

                Uri StartUri = new Uri(FacebookURL);
                Uri EndUri   = new Uri(CallbackUrl);

                WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                    WebAuthenticationOptions.None,
                    StartUri,
                    EndUri);

                if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    Debug.WriteLine(WebAuthenticationResult.ResponseData.ToString());
                    await GetFacebookUserNameAsync(WebAuthenticationResult.ResponseData.ToString());

                    LoggedIn = WebAccountState.Connected;
                }
            }
            catch (Exception Error)
            {
                Debug.WriteLine(Error.ToString());
            }
            return;
        }