private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            // for reference: if you ever need to get the correct callbackUri
            // for your app
            // var callbackUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();


            var client = new OAuth2Client(
                new Uri(ExpenseTrackerConstants.IdSrvAuthorize));

            string nonce = Guid.NewGuid().ToString() + DateTime.Now.Ticks.ToString();

            var startUrl = client.CreateAuthorizeUrl(
                "native",
                "id_token token",
                "openid roles expensetrackerapi",
                ExpenseTrackerConstants.ExpenseTrackerMobile,
                "state", nonce);


            WebAuthenticationBroker.AuthenticateAndContinue
            (
                new Uri(startUrl),
                new Uri(ExpenseTrackerConstants.ExpenseTrackerMobile),
                null,
                WebAuthenticationOptions.None);
        }
Esempio n. 2
0
        /// <summary>
        /// Begins a server-side authentication flow by navigating the
        /// <see cref="WebAuthenticationBroker"/> to the <paramref name="startUrl"/>.
        /// Considers if the <paramref name="useSingleSignOn"/> is being used and calls the
        /// correct overload of the <see cref="WebAuthenticationBroker"/>.
        /// </summary>
        /// <param name="startUrl">The URL that the browser-based control should
        /// first navigate to in order to start the authenication flow.
        /// </param>
        /// <param name="endUrl">The URL that indicates the authentication flow has
        /// completed. Upon being redirected to any URL that starts with the
        /// <paramref name="endUrl"/>, the browser-based control must stop navigating and
        /// return the response data to the <see cref="AuthenticationBroker"/>.
        /// </param>
        /// <param name="useSingleSignOn">Indicates if single sign-on should be used so
        /// that users do not have to re-enter his/her credentials every time.
        /// </param>
        /// <returns>
        /// The <see cref="WebAuthenticationResult"/> returned by the
        /// <see cref="WebAuthenticationBroker"/>.
        /// </returns>
        private Task <string> AuthenticateWithBroker(Uri startUrl, Uri endUrl, bool useSingleSignOn)
        {
            Debug.Assert(startUrl != null);
            Debug.Assert(endUrl != null);

            if (pendingLoginTask != null)
            {
                throw new InvalidOperationException(Resources.IAuthenticationBroker_LoginInProgress);
            }

            pendingLoginTask = new TaskCompletionSource <string>();

            if (useSingleSignOn)
            {
                Uri ssoEndUri   = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
                Uri ssoStartUrl = GetUrlWithQueryStringParameter(startUrl, "sso_end_uri", ssoEndUri.AbsoluteUri);
                WebAuthenticationBroker.AuthenticateAndContinue(ssoStartUrl, null, null, WebAuthenticationOptions.None);
            }
            else
            {
                WebAuthenticationBroker.AuthenticateAndContinue(startUrl, endUrl, null, WebAuthenticationOptions.None);
            }

            return(pendingLoginTask.Task);
        }
Esempio n. 3
0
        private async Task Login()
        {
            //Client ID of the Facebook App (retrieved from the Facebook Developers portal)
            //Required permissions
            var scope = "public_profile, email";

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

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


#if WINDOWS_PHONE_APP
            WebAuthenticationBroker.AuthenticateAndContinue(startUri, endUri, null, WebAuthenticationOptions.None);
#endif

#if WINDOWS_APP
            WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, endUri);
            await ParseAuthenticationResult(result);
#endif
        }
Esempio n. 4
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
        }
Esempio n. 5
0
        /// <summary>
        /// Execute login process through OAuth2 authentication mechanism
        /// (https://developer.gitter.im/docs/authentication)
        /// </summary>
        /// <returns>true: login success / false: login failed / null: exception occured</returns>
        public async Task <bool?> LoginAsync(string oauthKey, string oauthSecret)
        {
            try
            {
#if WINDOWS_PHONE_APP
                _oauthKey    = oauthKey;
                _oauthSecret = oauthSecret;
#endif

                string startUrl = $"https://gitter.im/login/oauth/authorize?client_id={oauthKey}&response_type=code&redirect_uri={AuthHelper.RedirectUrl}";
                var    startUri = new Uri(startUrl);
                var    endUri   = new Uri(AuthHelper.RedirectUrl);

#if WINDOWS_PHONE_APP
                WebAuthenticationBroker.AuthenticateAndContinue(startUri, endUri, null, WebAuthenticationOptions.None);
                return(await Task.FromResult <bool?>(null));
#endif
#if WINDOWS_APP
                var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, endUri);

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

                return(!string.IsNullOrWhiteSpace(_token));
#endif
            }
            catch
            {
                return(null);
            }
        }
Esempio n. 6
0
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            // for reference: if you ever need to get the correct callbackUri
            // for your app
            // var callbackUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();

            var client = new OAuth2Client(
                new Uri(ExpenseTrackerConstants.IdSrvAuthorizeWp));

            string nonce = Guid.NewGuid().ToString() + DateTime.Now.Ticks.ToString();

            var startUrl = client.CreateAuthorizeUrl(
                "native",                         //this client corresponds to client config on id srv level
                "id_token token",                 //Request an id token + access token
                "openid roles expensetrackerapi", //the access token should contain the id and roles scope
                //will call the user info end point for this

                //We no longer use the authorization code as this does not belong to the implicit flow
                //The WP client isn't a confidential client...
                //If you do ask for the authorization code, this flow will fail.

                //Ask for the expensetrackerapi scope to get it included in the access token
                ExpenseTrackerConstants.ExpenseTrackerMobile,
                "state", //With state you can pass through values
                nonce);  //Number only used once, this is used by the STS to prevent replay attacks

            WebAuthenticationBroker.AuthenticateAndContinue
            (
                new Uri(startUrl),
                new Uri(ExpenseTrackerConstants.ExpenseTrackerMobile),
                null,
                WebAuthenticationOptions.None);
        }
Esempio n. 7
0
        protected override void OnElementChanged(ElementChangedEventArgs <Page> e)
        {
            base.OnElementChanged(e);

            var app = (MixRadioActivity.App.Current as MixRadioActivity.App);

            WebAuthenticationBroker.AuthenticateAndContinue(app.ActivityViewModel.GetAuthUri(), new Uri(ApiKeys.OAuthRedirectUrl));
        }
        public void StartLoginFlow(LoginOptions loginOptions)
        {
            Uri loginUri    = new Uri(OAuth2.ComputeAuthorizationUrl(loginOptions));
            Uri callbackUri = new Uri(loginOptions.CallbackUrl);

            OAuth2.ClearCookies(loginOptions);
            WebAuthenticationBroker.AuthenticateAndContinue(loginUri, callbackUri, null, WebAuthenticationOptions.None);
        }
Esempio n. 9
0
        private void LaunchAuthentication()
        {
            var url = _vidMeClient.GetAuthUrl(Constants.ClientId, Constants.CallBackUrl, new List <Scope> {
                Scope.Videos, Scope.VideoUpload, Scope.Channels, Scope.Comments, Scope.Votes, Scope.Account, Scope.AuthManagement, Scope.ClientManagement
            });

            WebAuthenticationBroker.AuthenticateAndContinue(new Uri(url), new Uri(Constants.CallBackUrl), new ValueSet(), WebAuthenticationOptions.None);
        }
Esempio n. 10
0
        private async void Launch_Click(object sender, RoutedEventArgs e)
#endif
        {
            if (TwitterClientID.Text == "")
            {
                rootPage.NotifyUser("Please enter an Client ID.", NotifyType.StatusMessage);
            }
            else if (TwitterCallbackUrl.Text == "")
            {
                rootPage.NotifyUser("Please enter an Callback URL.", NotifyType.StatusMessage);
            }
            else if (TwitterClientSecret.Text == "")
            {
                rootPage.NotifyUser("Please enter an Client Secret.", NotifyType.StatusMessage);
            }

            try
            {
                string oauth_token = await GetTwitterRequestTokenAsync(TwitterCallbackUrl.Text, TwitterClientID.Text);

                string     TwitterUrl = "https://api.twitter.com/oauth/authorize?oauth_token=" + oauth_token;
                System.Uri StartUri   = new Uri(TwitterUrl);
                System.Uri EndUri     = new Uri(TwitterCallbackUrl.Text);

//                DebugPrint("Navigating to: " + TwitterUrl);
#if WINDOWS_PHONE_APP
                WebAuthenticationBroker.AuthenticateAndContinue(StartUri, EndUri, null, WebAuthenticationOptions.None);
#else
                WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                    WebAuthenticationOptions.None,
                    StartUri,
                    EndUri);

                if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    OutputToken(WebAuthenticationResult.ResponseData.ToString());
                    await GetTwitterUserNameAsync(WebAuthenticationResult.ResponseData.ToString());
                }
                else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                {
                    OutputToken("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString());
                }
                else
                {
                    OutputToken("Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseStatus.ToString());
                }
#endif
            }
            catch (Exception Error)
            {
                //
                // Bad Parameter, SSL/TLS Errors and Network Unavailable errors are to be handled here.
                //
                DebugPrint(Error.ToString());
            }
        }
        /// <summary>
        /// This method will be for logout from facebook
        /// </summary>
        public void FacebookLogout()
        {
            var _logoutUrl = GlobalVariable.fbclient.GetLogoutUrl(new
            {
                next         = "https://www.facebook.com/connect/login_success.html",
                access_token = GlobalVariable.FbAccessToken
            });

            WebAuthenticationBroker.AuthenticateAndContinue(_logoutUrl);
        }
Esempio n. 12
0
 private async void BtnFaceBookLogout_Click(object sender, RoutedEventArgs e)
 {
     _logoutUrl = fbclient.GetLogoutUrl(new
     {
         next         = "https://www.facebook.com/connect/login_success.html",
         access_token = ObjFBHelper.AccessToken
     });
     WebAuthenticationBroker.AuthenticateAndContinue(_logoutUrl);
     BtnLogin.Visibility  = Visibility.Visible;
     BtnLogout.Visibility = Visibility.Collapsed;
 }
        /// <summary>
        /// Startes the authorization process which will continue through an app
        /// activation.
        /// </summary>
        public static void AuthorizeAndContinue()
        {
            var authUri = DropboxOAuth2Helper.GetAuthorizeUri(
                OAuthResponseType.Token,
                App.AppKey,
                App.RedirectUri);

            WebAuthenticationBroker.AuthenticateAndContinue(
                authUri,
                App.RedirectUri);
        }
        public virtual void RequestAuthorizationCode()
        {
            var param = string.Format(PARAM_TEMPLATE, config.scope, Uri.EscapeDataString(config.redirectURL), Uri.EscapeDataString(config.clientId));
            var uri   = new Uri(config.baseURL + config.authzEndpoint).AbsoluteUri + param;

            var values = new ValueSet()
            {
                { "name", config.accountId }
            };

            WebAuthenticationBroker.AuthenticateAndContinue(new Uri(uri), new Uri(config.redirectURL), values, WebAuthenticationOptions.None);
        }
        private async void Launch_Click(object sender, RoutedEventArgs e)
#endif
        {
            if (GoogleClientID.Text == "")
            {
                rootPage.NotifyUser("Please enter an Client ID.", NotifyType.StatusMessage);
            }
            else if (GoogleCallbackUrl.Text == "")
            {
                rootPage.NotifyUser("Please enter an Callback URL.", NotifyType.StatusMessage);
            }

            try
            {
                String GoogleURL = "https://accounts.google.com/o/oauth2/auth?client_id=" + Uri.EscapeDataString(GoogleClientID.Text) + "&redirect_uri=" + Uri.EscapeDataString(GoogleCallbackUrl.Text) + "&response_type=code&scope=" + Uri.EscapeDataString("http://picasaweb.google.com/data");

                System.Uri StartUri = new Uri(GoogleURL);
                // When using the desktop flow, the success code is displayed in the html title of this end uri
                System.Uri EndUri = new Uri("https://accounts.google.com/o/oauth2/approval?");

                DebugPrint("Navigating to: " + GoogleURL);

#if WINDOWS_PHONE_APP
                WebAuthenticationBroker.AuthenticateAndContinue(StartUri, EndUri, null, WebAuthenticationOptions.None);
#else
                WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                    WebAuthenticationOptions.UseTitle,
                    StartUri,
                    EndUri);

                if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    OutputToken(WebAuthenticationResult.ResponseData.ToString());
                }
                else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                {
                    OutputToken("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString());
                }
                else
                {
                    OutputToken("Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseStatus.ToString());
                }
#endif
            }
            catch (Exception Error)
            {
                //
                // Bad Parameter, SSL/TLS Errors and Network Unavailable errors are to be handled here.
                //
                DebugPrint(Error.ToString());
            }
        }
Esempio n. 16
0
        public async Task LoginAndContinue()
        {
            if (DeviceTypeHelper.GetDeviceFormFactorType() == DeviceFormFactorType.Desktop)
            {
                WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, _loginUrl);

                ValidateAndProccessResult(result);
            }
            else
            {
                WebAuthenticationBroker.AuthenticateAndContinue(_loginUrl);
            }
        }
Esempio n. 17
0
        private async void Launch_Click(object sender, RoutedEventArgs e)
#endif
        {
            if (FacebookClientID.Text == "")
            {
                rootPage.NotifyUser("Please enter an Client ID.", NotifyType.StatusMessage);
            }
            else if (FacebookCallbackUrl.Text == "")
            {
                rootPage.NotifyUser("Please enter an Callback URL.", NotifyType.StatusMessage);
            }

            try
            {
                String FacebookURL = "https://www.facebook.com/dialog/oauth?client_id=" + Uri.EscapeDataString(FacebookClientID.Text) + "&redirect_uri=" + Uri.EscapeDataString(FacebookCallbackUrl.Text) + "&scope=read_stream&display=popup&response_type=token";

                System.Uri StartUri = new Uri(FacebookURL);
                System.Uri EndUri   = new Uri(FacebookCallbackUrl.Text);

                DebugPrint("Navigating to: " + FacebookURL);
#if WINDOWS_PHONE_APP
                WebAuthenticationBroker.AuthenticateAndContinue(StartUri, EndUri, null, WebAuthenticationOptions.None);
#else
                WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                    WebAuthenticationOptions.None,
                    StartUri,
                    EndUri);

                if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    OutputToken(WebAuthenticationResult.ResponseData.ToString());
                    await GetFacebookUserNameAsync(WebAuthenticationResult.ResponseData.ToString());
                }
                else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                {
                    OutputToken("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString());
                }
                else
                {
                    OutputToken("Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseStatus.ToString());
                }
#endif
            }
            catch (Exception Error)
            {
                //
                // Bad Parameter, SSL/TLS Errors and Network Unavailable errors are to be handled here.
                //
                DebugPrint(Error.ToString());
            }
        }
Esempio n. 18
0
        // http://msdn.microsoft.com/ja-jp/library/dn631755.aspx
        // http://dotnet.dzone.com/articles/how-use
        // http://www.cloudidentity.com/blog/2014/04/16/calling-office365-api-from-a-windows-phone-8-1-app/
        // http://msicc.net/?p=4054
        private void RedirectToAuthButton_Click(object sender, RoutedEventArgs e)
        {
            if (this.requestToken != null)
            {
                var redirectUrl = this.twitterOAuth.GetRedirectAuthUrl(this.requestToken);
                this.WriteLog(String.Format("Redirect URI:{0}", redirectUrl));

                Uri StartUri = new Uri(redirectUrl);
                Uri EndUri   = new Uri(TwitterOAuthConstants.OAuthCallbackUrl);
                //WebAuthenticationBroker.AuthenticateAndContinue(StartUri, EndUri, null, WebAuthenticationOptions.None);

                WebAuthenticationBroker.AuthenticateAndContinue(StartUri, EndUri);
            }
        }
Esempio n. 19
0
        private async Task ReadabilityAuthentication()
        {
            try
            {
                await _readabilityClient.GetRequestTokenAsync(Constants.Readability.CallBackUri);
            }
            catch (Exception ex)
            {
                Log.ErrorException("ReadabilityAuthentication()", ex);
                return;
            }

            var authUri = _readabilityClient.GenerateAuthenticationUri();

            WebAuthenticationBroker.AuthenticateAndContinue(authUri, new Uri(Constants.Readability.CallBackUri), new ValueSet(), WebAuthenticationOptions.None);
        }
        public async Task <Session> LoginAsync()
        {
            const string FacebookCallbackUrl = "https://m.facebook.com/connect/login_success.html";
            var          facebookUrl         = "https://www.facebook.com/dialog/oauth?client_id=" + Uri.EscapeDataString(Constants.FacebookAppId) + "&redirect_uri=" + Uri.EscapeDataString(FacebookCallbackUrl) + "&scope=public_profile,email&display=popup&response_type=token";

            var startUri = new Uri(facebookUrl);
            var endUri   = new Uri(FacebookCallbackUrl);

#if WINDOWS_PHONE_APP
            WebAuthenticationBroker.AuthenticateAndContinue(startUri, endUri, null, WebAuthenticationOptions.None);
            return(null);
#else
            var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, endUri);

            return(GetSession(webAuthenticationResult));
#endif
        }
        public void Authenticate(Uri authorizationUri, Uri redirectUri, IDictionary <string, object> headersMap, CallState callState)
        {
            ValueSet set = new ValueSet();

            foreach (string key in headersMap.Keys)
            {
                set[key] = headersMap[key];
            }

            try
            {
                WebAuthenticationBroker.AuthenticateAndContinue(authorizationUri, ReferenceEquals(redirectUri, Constant.SsoPlaceHolderUri) ? null : redirectUri, set, WebAuthenticationOptions.None);
            }
            catch (Exception ex)
            {
                throw new AdalException(AdalError.AuthenticationUiFailed, ex);
            }
        }
Esempio n. 22
0
        private void ProfileImage_Tapped(object sender, TappedRoutedEventArgs e)
        {
            FacebookClient fbclient = new FacebookClient();

            _logoutUrl = fbclient.GetLogoutUrl(new
            {
                next         = "https://www.facebook.com/connect/login_success.html",
                access_token = App.ObjFBHelper.AccessToken,
                //  redirect_uri =  App.ObjFBHelper._callbackUri.AbsoluteUri,
            });
            ProfileHelpers.IsLogin      = false;
            ProfileHelpers.ProfileImage = "";
            WebAuthenticationBroker.AuthenticateAndContinue(_logoutUrl);


            // Frame.Navigate(typeof(Login));
            //BtnLogin.Visibility = Visibility.Visible;
            //BtnLogout.Visibility = Visibility.Collapsed;
        }
        /// <summary>
        /// The dispatcher tick.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The event args</param>
        /// <remarks>http://stackoverflow.com/questions/23267918</remarks>
        private async void DispatcherTick(object sender, object e)
        {
            _dispatcherTimer.Stop();

            var token = await IsolatedStorage.GetToken();

            if (!string.IsNullOrEmpty(token))
            {
                ((Frame)Window.Current.Content).Navigate(typeof(RoomsPage));

                return;
            }

            var gitterUrl = string.Format("{0}{1}?response_type=code&redirect_uri={2}&client_id={3}", Constants.GitterBaseAddress, Constants.AuthEndPoint, Constants.RedirectUrl, Constants.ClientKey);

            var startUri = new Uri(gitterUrl);
            var endUri   = new Uri(Constants.RedirectUrl);

            WebAuthenticationBroker.AuthenticateAndContinue(startUri, endUri, null, WebAuthenticationOptions.None);
        }
Esempio n. 24
0
        public static void DoImplicitFlowAsync(
            Uri endpoint,
            string clientId,
            string responseType,
            string scope,
            Uri redirectUri)
        {
            var client = new OAuth2Client(endpoint);
            var state  = Guid.NewGuid().ToString("N");
            var nonce  = Guid.NewGuid().ToString("N");

            var startUri = client.CreateAuthorizeUrl(
                clientId: clientId,
                responseType: responseType,
                scope: scope,
                redirectUri: redirectUri.AbsoluteUri,
                state: state,
                nonce: nonce);

            try
            {
                // On Windows Phone 8.1, the AuthenticateAsync method isn't implemented on
                // the WebAuthenticationBroker.  Therefor, AuthenticateAndContinue is used.
                //
                // Callback = ContinueWebAuthentication in MainPage.xaml.cs

                WebAuthenticationBroker.AuthenticateAndContinue(
                    new Uri(startUri),
                    redirectUri,
                    null,
                    WebAuthenticationOptions.None
                    );
            }
            catch
            {
                // Bad Parameter, SSL/TLS Errors and Network Unavailable errors are to be handled here.
                throw;
            }
        }
        public void StartLoginFlow(LoginOptions loginOptions)
        {
            if (loginOptions == null || String.IsNullOrWhiteSpace(loginOptions.CallbackUrl) ||
                String.IsNullOrWhiteSpace(loginOptions.LoginUrl))
            {
                return;
            }
            try
            {
                var loginUri    = new Uri(OAuth2.ComputeAuthorizationUrl(loginOptions));
                var callbackUri = new Uri(loginOptions.CallbackUrl);
                WebAuthenticationBroker.AuthenticateAndContinue(loginUri, callbackUri, null,
                                                                WebAuthenticationOptions.None);
            }
            catch (Exception ex)
            {
                PlatformAdapter.SendToCustomLogger("AccountPage.StartLoginFlow - Exception occured", LoggingLevel.Critical);
                PlatformAdapter.SendToCustomLogger(ex, LoggingLevel.Critical);

                PlatformAdapter.Resolve <IAuthHelper>().StartLoginFlow();
            }
        }
Esempio n. 26
0
        private async Task PocketAuthentication()
        {
            try
            {
                var code = await _pocketClient.GetRequestCode();
            }
            catch (Exception ex)
            {
                Log.ErrorException("PocketAuthentication", ex);
                return;
            }

            var authUri = _pocketClient.GenerateAuthenticationUri();

#if WINDOWS_PHONE_APP
            WebAuthenticationBroker.AuthenticateAndContinue(authUri, new Uri(Constants.Pocket.CallBackUri), new ValueSet(), WebAuthenticationOptions.None);
#else
            var result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, authUri);

            await GetAuthenticationToken();
#endif
        }
        public void Authenticate(Uri authorizationUri, Uri redirectUri, IDictionary <string, object> headersMap, CallState callState)
        {
            ValueSet set = new ValueSet();

            foreach (string key in headersMap.Keys)
            {
                set[key] = headersMap[key];
            }

            if (redirectUri.AbsoluteUri == WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri)
            {
                // SSO Mode

                try
                {
                    WebAuthenticationBroker.AuthenticateAndContinue(authorizationUri, null, set, WebAuthenticationOptions.None);
                }
                catch (FileNotFoundException ex)
                {
                    throw new AdalException(AdalError.AuthenticationUiFailed, ex);
                }
            }
            else if (redirectUri.Scheme == "ms-app")
            {
                throw new ArgumentException(AdalErrorMessage.RedirectUriAppIdMismatch, "redirectUri");
            }
            else
            {
                try
                {
                    // Non-SSO Mode
                    WebAuthenticationBroker.AuthenticateAndContinue(authorizationUri, redirectUri, set, WebAuthenticationOptions.None);
                }
                catch (FileNotFoundException ex)
                {
                    throw new AdalException(AdalError.AuthenticationUiFailed, ex);
                }
            }
        }
Esempio n. 28
0
        public async Task StartOAuthFlow()
        {
            Exception exIfAny = null;

            try
            {
                string state = Guid.NewGuid().ToString("N");
                VaultManager.Save(VaultStateResourceKey, VaultDefaultUnusedUserName, state);

                // Delete the now "old" code and access token info record from the vault before proceeding
                VaultManager.Delete(VaultTokenCodeResourceKey, VaultDefaultUnusedUserName);
                VaultManager.Delete(VaultTokenInfoResourceKey, VaultDefaultUnusedUserName);
                _gitHubClient.Credentials = Credentials.Anonymous;

                var uri = FormatGitHubLoginUrl(GhOAuthConfiguration.ClientId,
                                               GhOAuthConfiguration.RedirectUri,
                                               DeclareScopes(),
                                               state);

                Uri requestUri  = new Uri(uri);
                Uri callbackUri = new Uri(GhOAuthConfiguration.RedirectUri);

                WebAuthenticationBroker.AuthenticateAndContinue(requestUri,
                                                                callbackUri,
                                                                null,
                                                                WebAuthenticationOptions.None);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                exIfAny = ex;
            }

            if (null != exIfAny)
            {
                await _messageService.ShowAsync(exIfAny.Message);
            }
        }
        /// <summary>Asynchronously receives the authorization code.</summary>
        /// <param name="url">The authorization code request URL.</param>
        /// <param name="tcs">Task completion source whose result will be set to the authorization code.</param>
        private async Task ReceiveCodeAsync(AuthorizationCodeRequestUrl url,
                                            TaskCompletionSource <AuthorizationCodeResponseUrl> tcs)
        {
            var result = await PasswordVaultDataStore.Default.GetAsync <SerializableWebAuthResult>(
                SerializableWebAuthResult.Name);

            if (result == null)
            {
                // We should run WebAuthenticationBroker.AuthenticateAndContinue from the UI thread ONLY.
                await InvokeFromUIThread(() => WebAuthenticationBroker.AuthenticateAndContinue(url.Build(),
                                                                                               new Uri(GoogleAuthConsts.LocalhostRedirectUri), null, WebAuthenticationOptions.None));

                // No need to return anything, cause the application is going to be suspended now.
                return;
            }

            const string Code  = "code=";
            const string Error = "error=";
            // Get the index of the error or the code.
            var index = result.ResponseData.IndexOf(Code);

            index = index != -1 ? index : result.ResponseData.IndexOf(Error);

            if (index != -1)
            {
                tcs.SetResult(new AuthorizationCodeResponseUrl(result.ResponseData.Substring(index)));
                return;
            }

            tcs.SetException(new TokenResponseException(
                                 new TokenErrorResponse
            {
                Error            = result.ResponseStatus.ToString(),
                ErrorDescription = "The WebAuthenticationBroker didn't return a code or an error. Details: " +
                                   result.ResponseErrorDetail,
            }));
        }
Esempio n. 30
0
        public async Task <Session> LoginAsync()
        {
            var googleUrl = new StringBuilder();

            googleUrl.Append("https://accounts.google.com/o/oauth2/auth?client_id=");
            googleUrl.Append(Uri.EscapeDataString(Constants.GoogleClientId));
            googleUrl.Append("&scope=openid%20email%20profile");
            googleUrl.Append("&redirect_uri=");
            googleUrl.Append(Uri.EscapeDataString(Constants.GoogleCallbackUrl));
            googleUrl.Append("&state=foobar");
            googleUrl.Append("&response_type=code");

            var startUri = new Uri(googleUrl.ToString());

#if WINDOWS_APP
            var endUri = new Uri("https://accounts.google.com/o/oauth2/approval?");
            var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.UseTitle, startUri, endUri);

            return(await GetSessionAsync(webAuthenticationResult));
#else
            WebAuthenticationBroker.AuthenticateAndContinue(startUri, new Uri(Constants.GoogleCallbackUrl), null, WebAuthenticationOptions.None);
            return(null);
#endif
        }