Exemple #1
0
        /// <summary>
        /// Implements <see cref="IDevOpsIntegration.HandleLoginAsync(CredentialPromptType, Uri)"/>
        /// </summary>
        public async Task HandleLoginAsync(CredentialPromptType showDialog = CredentialPromptType.DoNotPrompt, Uri serverUri = null)
        {
            serverUri = serverUri ?? Configuration.SavedConnection.ServerUri;

            if (serverUri == null)
            {
                return;
            }

            // If the main window is always on top, then an error occurs where
            //  the login dialog is not a child of the main window, so we temporarily
            //  turn topmost off and turn it back on after logging in
            bool oldTopmost = false;

            Application.Current.Dispatcher.Invoke(() =>
            {
                oldTopmost = Application.Current.MainWindow.Topmost;
                Application.Current.MainWindow.Topmost = false;
            });

            try
            {
                await ConnectToAzureDevOpsAccount(serverUri, showDialog).ConfigureAwait(true);
                await PopulateUserProfile().ConfigureAwait(true);
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
            {
                ex.ReportException();
                FlushToken(serverUri);
            }
#pragma warning restore CA1031 // Do not catch general exception types

            Application.Current.Dispatcher.Invoke(() => Application.Current.MainWindow.Topmost = oldTopmost);
        }
Exemple #2
0
 /// <summary>
 /// Initializes a new <c>VssCredentials</c> instance with the specified windows and issued token
 /// credential.
 /// </summary>
 /// <param name="federatedCredential">The federated credential to use for authentication</param>
 /// <param name="promptType">CredentialPromptType.PromptIfNeeded if interactive prompts are allowed; otherwise, CredentialProptType.DoNotPrompt</param>
 /// <param name="scheduler">An optional <c>TaskScheduler</c> to ensure credentials prompting occurs on the UI thread</param>
 public VssCredentials(
     FederatedCredential federatedCredential,
     CredentialPromptType promptType,
     TaskScheduler scheduler)
     : this(federatedCredential, promptType, scheduler, null)
 {
 }
Exemple #3
0
 public OnlineIdAuthenticationProvider(
     string[] scopes, PromptType promptType = PromptType.PromptIfNeeded)
     : base(null, null, scopes)
 {
     this.authenticator        = new OnlineIdAuthenticator();
     this.credentialPromptType = (CredentialPromptType)promptType;
 }
Exemple #4
0
        /// <summary>
        /// Initializes a new <c>VssCredentials</c> instance with the specified windows and issued token
        /// credential.
        /// </summary>
        /// <param name="federatedCredential">The federated credential to use for authentication</param>
        /// <param name="promptType">CredentialPromptType.PromptIfNeeded if interactive prompts are allowed; otherwise, CredentialProptType.DoNotPrompt</param>
        /// <param name="scheduler">An optional <c>TaskScheduler</c> to ensure credentials prompting occurs on the UI thread</param>
        /// <param name="credentialPrompt">An optional <c>IVssCredentialPrompt</c> to perform prompting for credentials</param>
        public VssCredentials(
            FederatedCredential federatedCredential,
            CredentialPromptType promptType,
            TaskScheduler scheduler,
            IVssCredentialPrompt credentialPrompt)
        {
            this.PromptType = promptType;

            if (promptType == CredentialPromptType.PromptIfNeeded && scheduler == null)
            {
                // If we use TaskScheduler.FromCurrentSynchronizationContext() here and this is executing under the UI
                // thread, for example from an event handler in a WinForms applications, this TaskScheduler will capture
                // the UI SyncrhonizationContext whose MaximumConcurrencyLevel is 1 and only has a single thread to
                // execute queued work. Then, if the UI thread invokes one of our synchronous methods that are just
                // wrappers that block until the asynchronous overload returns, and if the async Task queues work to
                // this TaskScheduler, like GitHub.Services.CommonGetTokenOperation.GetTokenAsync does,
                // this will produce an immediate deadlock. It is a much safer choice to use TaskScheduler.Default here
                // as it uses the .NET Framework ThreadPool to execute queued work.
                scheduler = TaskScheduler.Default;
            }

            if (federatedCredential != null)
            {
                m_federatedCredential           = federatedCredential;
                m_federatedCredential.Scheduler = scheduler;
                m_federatedCredential.Prompt    = credentialPrompt;
            }

            m_thisLock = new object();
        }
Exemple #5
0
        internal async Task HandleLoginAsync(CredentialPromptType showDialog = CredentialPromptType.DoNotPrompt, Uri serverUri = null)
        {
            serverUri = serverUri ?? Configuration.SavedConnection.ServerUri;

            if (serverUri == null)
            {
                return;
            }

            // If the main window is always on top, then an error occurs where
            //  the login dialog is not a child of the main window, so we temporarily
            //  turn topmost off and turn it back on after logging in
            bool oldTopmost = false;

            Application.Current.Dispatcher.Invoke(() =>
            {
                oldTopmost = Application.Current.MainWindow.Topmost;
                Application.Current.MainWindow.Topmost = false;
            });

            try
            {
                await FileIssueHelpers.ConnectAsync(serverUri, showDialog).ConfigureAwait(true);

                await FileIssueHelpers.PopulateUserProfileAsync().ConfigureAwait(true);
            }
            catch (Exception)
            {
                FileIssueHelpers.FlushToken(serverUri);
            }

            Application.Current.Dispatcher.Invoke(() => Application.Current.MainWindow.Topmost = oldTopmost);
        }
Exemple #6
0
 /// <summary>
 /// Creates an unauthenticated client for use in Store apps that uses the OnlineIdAuthenticator API for authentication.
 /// </summary>
 /// <param name="appId">The application ID for Microsoft account authentication.</param>
 /// <param name="scopes">The requested scopes for Microsoft account authentication.</param>
 /// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending HTTP requests.</param>
 /// <param name="promptType">The credential prompt type (show or hide the credential prompt user interface)</param>
 /// <returns>The <see cref="IOneDriveClient"/> for the session.</returns>
 public static IOneDriveClient GetUniversalClient(
     string[] scopes,
     string returnUrl                = null,
     IHttpProvider httpProvider      = null,
     CredentialPromptType promptType = CredentialPromptType.PromptIfNeeded)
 {
     return(OneDriveClientExtensions.GetClientUsingOnlineIdAuthenticator(scopes, returnUrl, httpProvider, promptType));
 }
Exemple #7
0
 public MainPage()
 {
     this.InitializeComponent();
     Current          = this;
     _authenticator   = new OnlineIdAuthenticator();
     PromptType       = CredentialPromptType.PromptIfNeeded;
     AccessToken      = null;
     NeedsToGetTicket = true;
 }
        public Scenario02_JwtToken()
        {
            this.InitializeComponent();

            _authenticator = new OnlineIdAuthenticator();

            PromptType = CredentialPromptType.PromptIfNeeded;
            SignInOptions.SelectedItem = PromptIfNeeded;

            NeedsToGetTicket = true;
            SignOutButton.Visibility = CanSignOut ? Visibility.Visible : Visibility.Collapsed;
        }
        public Scenario01_DelegationToken()
        {
            this.InitializeComponent();

            _authenticator = new OnlineIdAuthenticator();

            PromptType = CredentialPromptType.PromptIfNeeded;
            SignInOptions.SelectedItem = PromptIfNeeded;
            AccessToken              = null;
            NeedsToGetTicket         = true;
            SignOutButton.Visibility = CanSignOut ? Visibility.Visible : Visibility.Collapsed;
        }
Exemple #10
0
 /// <summary>
 /// Creates an unauthenticated client that uses the OnlineIdAuthenticator API for authentication.
 /// </summary>
 /// <param name="scopes">The requested scopes for Microsoft account authentication.</param>
 /// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending HTTP requests.</param>
 /// <param name="promptType">The credential prompt type (show or hide the credential prompt user interface)</param>
 /// <returns>The <see cref="IOneDriveClient"/> for the session.</returns>
 public static IOneDriveClient GetClientUsingOnlineIdAuthenticator(
     string[] scopes,
     string returnUrl                = null,
     IHttpProvider httpProvider      = null,
     CredentialPromptType promptType = CredentialPromptType.PromptIfNeeded)
 {
     return(new OneDriveClient(
                new AppConfig {
         MicrosoftAccountScopes = scopes, MicrosoftAccountPromptType = promptType
     },
                httpProvider: httpProvider ?? new HttpProvider(),
                serviceInfoProvider: new OnlineIdServiceInfoProvider()));
 }
Exemple #11
0
 /// <summary>
 /// Connects to the AzureDevOps server at the given url (e.g. https://myaccount.visualstudio.com)
 ///     If prompt is true, then we may prompt if needed - otherwise, we turn prompting off on credentials
 /// </summary>
 /// <param name="url">AzureDevOps URL to connect to</param>
 /// <param name="prompt">whether user should see any login prompts if needed</param>
 /// <returns></returns>
 internal Task ConnectToAzureDevOpsAccount(Uri url, CredentialPromptType prompt = CredentialPromptType.PromptIfNeeded)
 {
     lock (myLock)
     {
         // reset connection state
         Disconnect();
         var credentials = new VssClientCredentials(false);
         credentials.Storage    = new VssClientCredentialStorage();
         credentials.PromptType = prompt;
         _baseServerConnection  = new VssConnection(url, credentials);
         return(_baseServerConnection.ConnectAsync());
     }
 }
        private void SignInOptions_SelectionChanged(object sender, RoutedEventArgs e)
        {
            if (SignInOptions.SelectedItem == PromptIfNeeded)
            {
                PromptType = CredentialPromptType.PromptIfNeeded;
            }
            else if (SignInOptions.SelectedItem == DontPrompt)
            {
                PromptType = CredentialPromptType.DoNotPrompt;
            }
            else if (SignInOptions.SelectedItem == RetypeCredentials)
            {
                PromptType = CredentialPromptType.RetypeCredentials;
            }

            SignInButton.Visibility = Visibility.Visible;
        }
        private async Task <string> GetAccessToken(string scopes, bool silent)
        {
            string ticket = string.Empty;

            Debug.Assert(!string.IsNullOrEmpty(scopes), "scopes is null or empty.");

            CredentialPromptType promptType = silent ? CredentialPromptType.DoNotPrompt : CredentialPromptType.PromptIfNeeded;
            var ticketRequests = new List <OnlineIdServiceTicketRequest>();

            ticketRequests.Add(new OnlineIdServiceTicketRequest(scopes, "DELEGATION"));

            UserIdentity identity = await this.authenticator.AuthenticateUserAsync(ticketRequests, promptType);

            if (identity.Tickets != null && identity.Tickets.Count > 0)
            {
                ticket = identity.Tickets[0].Value;
            }

            return(ticket);
        }
        private void SignInOptions_SelectionChanged(object sender, RoutedEventArgs e)
        {
            if (SignInOptions.SelectedItem == PromptIfNeeded)
            {
                PromptType = CredentialPromptType.PromptIfNeeded;
            }
            else if (SignInOptions.SelectedItem == DontPrompt)
            {
                PromptType = CredentialPromptType.DoNotPrompt;
            }
            else if (SignInOptions.SelectedItem == RetypeCredentials)
            {
                PromptType = CredentialPromptType.RetypeCredentials;
            }

            SignInButton.Visibility = Visibility.Visible;
        }
 /// <summary>
 /// Creates an unauthenticated client for use in Store apps that uses the OnlineIdAuthenticator API for authentication.
 /// </summary>
 /// <param name="appId">The application ID for Microsoft account authentication.</param>
 /// <param name="scopes">The requested scopes for Microsoft account authentication.</param>
 /// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending HTTP requests.</param>
 /// <param name="promptType">The credential prompt type (show or hide the credential prompt user interface)</param>
 /// <returns>The <see cref="IOneDriveClient"/> for the session.</returns>
 public static IOneDriveClient GetUniversalClient(
     string[] scopes,
     string returnUrl = null,
     IHttpProvider httpProvider = null,
     CredentialPromptType promptType = CredentialPromptType.PromptIfNeeded)
 {
     return OneDriveClientExtensions.GetClientUsingOnlineIdAuthenticator(scopes, returnUrl, httpProvider, promptType);
 }
 /// <summary>
 /// Creates an unauthenticated client that uses the OnlineIdAuthenticator API for authentication.
 /// </summary>
 /// <param name="scopes">The requested scopes for Microsoft account authentication.</param>
 /// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending HTTP requests.</param>
 /// <param name="promptType">The credential prompt type (show or hide the credential prompt user interface)</param>
 /// <returns>The <see cref="IOneDriveClient"/> for the session.</returns>
 public static IOneDriveClient GetClientUsingOnlineIdAuthenticator(
     string[] scopes,
     string returnUrl = null,
     IHttpProvider httpProvider = null,
     CredentialPromptType promptType = CredentialPromptType.PromptIfNeeded)
 {
     return new OneDriveClient(
         new AppConfig { MicrosoftAccountScopes = scopes, MicrosoftAccountPromptType = promptType },
         httpProvider: httpProvider ?? new HttpProvider(),
         serviceInfoProvider: new OnlineIdServiceInfoProvider());
 }
Exemple #17
0
		/// <summary>
		/// Gets a valid authentication token. Also refreshes the access token if it has expired.
		/// </summary>
		/// <remarks>
		/// Used by the API request generators before making calls to the OneNote APIs.
		/// </remarks>
		/// <returns>valid authentication token</returns>
		internal static async Task<string> GetAuthToken()
		{
			if (String.IsNullOrWhiteSpace(_accessToken))
			{
				try
				{
					var serviceTicketRequest = new OnlineIdServiceTicketRequest(Scopes, "DELEGATION");
					var result =
						await Authenticator.AuthenticateUserAsync(new[] { serviceTicketRequest }, credPrompt);
					if (result.Tickets[0] != null)
					{
						_accessToken = result.Tickets[0].Value;
						_accessTokenExpiration = DateTimeOffset.UtcNow.AddMinutes(AccessTokenApproxExpiresInMinutes);
					}
				}
				catch (Exception ex)
				{
					// Authentication failed
					if (Debugger.IsAttached)
						Debugger.Break();
				}
			}
			await RefreshAuthTokenIfNeeded();

            credPrompt = CredentialPromptType.PromptIfNeeded;

            return _accessToken;
		}
Exemple #18
0
		internal static async Task SignOut()
		{
			if (IsSignedIn)
			{
				_accessToken = null;
				await Authenticator.SignOutUserAsync();
                credPrompt = CredentialPromptType.RetypeCredentials;
            }
		}
Exemple #19
0
 /// <summary>
 /// Initializes a new <c>VssCredentials</c> instance with the specified windows and issued token
 /// credential.
 /// </summary>
 /// <param name="federatedCredential">The federated credential to use for authentication</param>
 /// <param name="promptType">CredentialPromptType.PromptIfNeeded if interactive prompts are allowed, otherwise CredentialProptType.DoNotPrompt</param>
 public VssCredentials(
     FederatedCredential federatedCredential,
     CredentialPromptType promptType)
     : this(federatedCredential, promptType, null)
 {
 }
Exemple #20
0
 public static Task ConnectAsync(Uri uri, CredentialPromptType prompt)
 {
     return(AzureDevOps.ConnectToAzureDevOpsAccount(uri, prompt));
 }
Exemple #21
0
        private static async Task<MobileServiceUser> DoLoginAsync(CredentialPromptType promptType)
        {
            MobileServiceUser user = null;
            var authenticator = new OnlineIdAuthenticator();
            var mobileServicesTicket = new OnlineIdServiceTicketRequest("wl.signin", "DELEGATION");

            var ticketRequests = new List<OnlineIdServiceTicketRequest> {mobileServicesTicket};

            var authResult = await authenticator.AuthenticateUserAsync(ticketRequests, promptType);

            if ((authResult.Tickets.Count == 1) && (authResult.Tickets[0].ErrorCode == 0))
            {
                var accessToken = authResult.Tickets[0];

                var payload = new JObject
                {
                    ["access_token"] = accessToken.Value
                };

                user = await MobileService.Client.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount, payload);

                LegacyUserId.Value = authResult.SafeCustomerId;
            }

            return user;
        }