Exemplo n.º 1
0
        private static async Task <ServiceClientCredentials> GetAzureCredentials()
        {
            var activeDirectoryClientSettings    = ActiveDirectoryClientSettings.UsePromptOnly(ConfigurationManager.AppSettings["ClientId"], new Uri("urn:ietf:wg:oauth:2.0:oob"));
            ServiceClientCredentials credentials = await UserTokenProvider.LoginWithPromptAsync(ConfigurationManager.AppSettings["ActiveDirectoryTenantId"], activeDirectoryClientSettings);

            return(credentials);
        }
Exemplo n.º 2
0
        public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var tokenAudience = new Uri(this.Environment.ManagementEndpoint);

            if (request.RequestUri.AbsoluteUri.StartsWith(this.Environment.GraphEndpoint,
                                                          StringComparison.OrdinalIgnoreCase))
            {
                tokenAudience = new Uri(this.Environment.GraphEndpoint);
            }
            else
            {
                var hostMatch = VaultHostRegex.Match(request.RequestUri.Authority);
                if (hostMatch.Success)
                {
                    tokenAudience = new Uri($"{request.RequestUri.Scheme}://{hostMatch.Groups[2].Value}");
                }
            }

            if (!this.credentialsCache.ContainsKey(tokenAudience))
            {
                var clientSettings = new ActiveDirectoryClientSettings
                {
                    ClientId          = WellKnownClientId,
                    ClientRedirectUri = new Uri("urn:ietf:wg:oauth:2.0:oob"),
                    PromptBehavior    = this.promptBehavior
                };

                var serviceSettings = ActiveDirectoryServiceSettings.Azure;
                serviceSettings.TokenAudience = tokenAudience;

                this.credentialsCache[tokenAudience] = await KvTokenProvider.LoginWithPromptAsync(this.TenantId, clientSettings, serviceSettings, TokenCache.DefaultShared);
            }

            await this.credentialsCache[tokenAudience].ProcessHttpRequestAsync(request, cancellationToken);
        }
Exemplo n.º 3
0
        private void ConnectMenuItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // User login via interactive popup
                // Authenticate using an an Azure AD domain and client ID that is available by default for all Azure subscriptions
                SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
                tenant = this.txtTenantID.Text;
                var nativeClientApp_clientId      = "1950a258-227b-4e31-a9cf-717495945fc2";
                var activeDirectoryClientSettings = ActiveDirectoryClientSettings.UsePromptOnly(nativeClientApp_clientId, new Uri("urn:ietf:wg:oauth:2.0:oob"));
                var creds = UserTokenProvider.LoginWithPromptAsync(tenant, activeDirectoryClientSettings).Result;
                this.uploadMenuItem.IsEnabled      = true;
                this.downloadMenuItem.IsEnabled    = true;
                this.listFilesMenuItem.IsEnabled   = true;
                this.getFileInfoMenuItem.IsEnabled = true;

                // Create client objects and set the subscription ID
                adlsClient           = new DataLakeStoreAccountManagementClient(creds);
                adlsFileSystemClient = new DataLakeStoreFileSystemManagementClient(creds);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Exception {ex.Message}", "Connect Failure", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 4
0
        //see: https://azure.microsoft.com/en-us/resources/samples/data-lake-analytics-dotnet-auth-options/
        private static ServiceClientCredentials GetCreds_User_Popup(
            string tenant,
            System.Uri tokenAudience,
            string clientId,
            PromptBehavior promptBehavior = PromptBehavior.Auto)
        {
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

            var clientSettings = new ActiveDirectoryClientSettings
            {
                ClientId          = clientId,
                ClientRedirectUri = new System.Uri("urn:ietf:wg:oauth:2.0:oob"),
                PromptBehavior    = promptBehavior
            };

            var serviceSettings = ActiveDirectoryServiceSettings.Azure;

            serviceSettings.TokenAudience = tokenAudience;

            var creds = UserTokenProvider.LoginWithPromptAsync(
                tenant,
                clientSettings,
                serviceSettings).GetAwaiter().GetResult();

            return(creds);
        }
Exemplo n.º 5
0
 /// <summary>
 /// Log in to Azure active directory with both user account and authentication credentials provided by the user.  This call may display a
 /// credentials dialog, depending on the supplied client settings and the state of the token cache and user cookies.
 /// </summary>
 /// <param name="domain">The domain to authenticate against.</param>
 /// <param name="clientSettings">The client settings to use for authentication. These determine when a dialog will be displayed.</param>
 /// <param name="serviceSettings">The settings for ad service, including endpoint and token audience</param>
 /// <param name="cache">The token cache to target during authentication.</param>
 /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the given credentials.</returns>
 public static async Task <ServiceClientCredentials> LoginWithPromptAsync(string domain,
                                                                          ActiveDirectoryClientSettings clientSettings,
                                                                          ActiveDirectoryServiceSettings serviceSettings, TokenCache cache)
 {
     return(await LoginWithPromptAsync(domain, clientSettings, serviceSettings,
                                       UserIdentifier.AnyUser, cache));
 }
Exemplo n.º 6
0
        public ActiveDirectoryClientSettings GetADClientSettings()
        {
            ActiveDirectoryClientSettings adClient = new ActiveDirectoryClientSettings()
            {
                ClientId          = this.ClientId,
                ClientRedirectUri = new Uri("urn:ietf:wg:oauth:2.0:oob"),
                PromptBehavior    = PromptBehavior.Always
            };

            return(adClient);
        }
        public void AutoPromptClientSettingsWillPromptIfNecessary()
        {
            var clientId  = Guid.NewGuid().ToString();
            var clientUri = new Uri("https://www.contoso.com/callbacks/");
            var settings  = ActiveDirectoryClientSettings.UseCacheCookiesOrPrompt(clientId, clientUri);

            Assert.Equal(clientId, settings.ClientId);
            Assert.Equal(clientUri, settings.ClientRedirectUri);
            Assert.Equal(PromptBehavior.Auto, settings.PromptBehavior);
            Assert.Equal(ActiveDirectoryClientSettings.EnableEbdMagicCookie, settings.AdditionalQueryParameters);
        }
        public void PromptOnlyClientSettingsWillAlwaysPrompt()
        {
            var clientId  = Guid.NewGuid().ToString();
            var clientUri = new Uri("https://www.contoso.com/callbacks/");
            var settings  = ActiveDirectoryClientSettings.UsePromptOnly(clientId, clientUri);

            Assert.Equal(clientId, settings.ClientId);
            Assert.Equal(clientUri, settings.ClientRedirectUri);
            Assert.Equal(PromptBehavior.Always, settings.PromptBehavior);
            Assert.Equal(ActiveDirectoryClientSettings.EnableEbdMagicCookie, settings.AdditionalQueryParameters);
        }
Exemplo n.º 9
0
        public async void loginAsync()
        {
            try
            {
                ActiveDirectoryClientSettings activeDirectoryClientSettings = new ActiveDirectoryClientSettings(clientID, new Uri(redirectUri));
                activeDirectoryClientSettings.PromptBehavior = Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior.Always;
                activeDirectoryClientSettings.OwnerWindow    = this;


                ServiceClientCredentials credentials = await UserTokenProvider.LoginWithPromptAsync(activeDirectoryClientSettings);

                //MessageBox.Show(credentials.TenantId);

                //ResourceManagementClient resourceManagementClient = new Microsoft.Azure.Management.ResourceManager.ResourceManagementClient(credentials);

                SubscriptionClient subClient = new SubscriptionClient(credentials);


                var subs = await subClient.Subscriptions.ListAsync();



                //TenantsOperationsExtensions

                //{
                //    SubscriptionId = SubscriptionId,
                //    GenerateClientRequestId = true,
                //    LongRunningOperationRetryTimeout = 60 * 6
                //};

                //AzureCredentials azureCredentials = new AzureCredentials(credentials, credentials, "common", AzureEnvironment.AzureGlobalCloud);

                //string tenant = Azure
                //    .Authenticate(azureCredentials)
                //    .TenantId;

                //MessageBox.Show(tenant);


                //var serviceClient = await credentials.InitializeServiceClient();

                MessageBox.Show(credentials.ToString());
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }



            //azureCredentials = new AzureCredentials(credentials, credentials, tenantID, AzureEnvironment.AzureGlobalCloud);
        }
Exemplo n.º 10
0
        public void ClientSettingsDefaultToAutoPrompt()
        {
            var clientId  = Guid.NewGuid().ToString();
            var clientUri = new Uri("https://www.contoso.com/callbacks/");
            var settings  = new ActiveDirectoryClientSettings(clientId, clientUri);

            Assert.Equal(clientId, settings.ClientId);
            Assert.Equal(clientUri, settings.ClientRedirectUri);
#if !PORTABLE
            Assert.Equal(PromptBehavior.Auto, settings.PromptBehavior);
#endif
            Assert.Equal(ActiveDirectoryClientSettings.EnableEbdMagicCookie, settings.AdditionalQueryParameters);
        }
Exemplo n.º 11
0
        // Login with a dialog user interface
        public static Microsoft.Rest.ServiceClientCredentials InteractiveLogin()
        {
            // Uses the client ID of an existing AAD "Native Client" application that is present by default in all AAD accounts.
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            var domain = "common";
            var nativeClientApp_clientId      = "1950a258-227b-4e31-a9cf-717495945fc2";
            var activeDirectoryClientSettings = ActiveDirectoryClientSettings.UsePromptOnly(nativeClientApp_clientId, new Uri("urn:ietf:wg:oauth:2.0:oob"));

            //TODO: 4. Display the dialog to prompt user login
            var creds = UserTokenProvider.//...;

                        return(creds);
        }
Exemplo n.º 12
0
        public void NoPromptClientSettingsWillNeverPrompt()
        {
            var clientId  = Guid.NewGuid().ToString();
            var clientUri = new Uri("https://www.contoso.com/callbacks/");
            var settings  = ActiveDirectoryClientSettings.UseCacheOrCookiesOnly(clientId, clientUri);

            Assert.Equal(clientId, settings.ClientId);
            Assert.Equal(clientUri, settings.ClientRedirectUri);
#if !PORTABLE
            Assert.Equal(PromptBehavior.Never, settings.PromptBehavior);
#endif
            Assert.Equal(ActiveDirectoryClientSettings.EnableEbdMagicCookie, settings.AdditionalQueryParameters);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Run interactive login
        /// </summary>
        /// <param name="tenant"></param>
        /// <param name="aadServiceSettings"></param>
        /// <param name="graphAADServiceSettings"></param>
        private void InteractiveLogin(string tenant, string PsClientId,
                                      ActiveDirectoryServiceSettings aadServiceSettings,
                                      ActiveDirectoryServiceSettings graphAADServiceSettings)
        {
//#if FullNetFx
#if net452
            ActiveDirectoryClientSettings clientSettings = new ActiveDirectoryClientSettings()
            {
                ClientId          = PsClientId,
                ClientRedirectUri = new Uri("urn:ietf:wg:oauth:2.0:oob"),
                PromptBehavior    = PromptBehavior.Always
            };

            TaskScheduler scheduler;
            if (SynchronizationContext.Current != null)
            {
                scheduler = TaskScheduler.FromCurrentSynchronizationContext();
            }
            else
            {
                scheduler = TaskScheduler.Current;
            }

            Task <TokenCredentials> mgmAuthResult = Task.Run(async() => (TokenCredentials)await UserTokenProvider
                                                             .LoginWithPromptAsync(this.Tenant,
                                                                                   clientSettings,
                                                                                   aadServiceSettings, () => { return(scheduler); }).ConfigureAwait(continueOnCapturedContext: false));

            this.TokenInfo[TokenAudience.Management] = mgmAuthResult.Result;
            this.ConnectionString.KeyValuePairs[ConnectionStringKeys.UserIdKey] = this.TokenInfo[TokenAudience.Management].CallerId;

            try
            {
                Task <TokenCredentials> graphAuthResult = Task.Run(async() => (TokenCredentials)await UserTokenProvider
                                                                   .LoginWithPromptAsync(this.Tenant,
                                                                                         clientSettings,
                                                                                         graphAADServiceSettings, () => { return(scheduler); }).ConfigureAwait(continueOnCapturedContext: true));
                this.TokenInfo[TokenAudience.Graph] = graphAuthResult.Result;
            }
            catch
            {
                // Not all accounts are registered to have access to Graph endpoints.
            }
#endif
        }
Exemplo n.º 14
0
        /*
         *  Interactive: User popup
         *  (using a token cache to reuse/save session state)
         */
        private static ServiceClientCredentials GetCredsInteractivePopup(string domain, Uri tokenAudience, TokenCache tokenCache, PromptBehavior promptBehavior = PromptBehavior.Auto)
        {
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

            var clientSettings = new ActiveDirectoryClientSettings
            {
                ClientId          = azure_powershell_clientid,
                ClientRedirectUri = new Uri("urn:ietf:wg:oauth:2.0:oob"),
                PromptBehavior    = promptBehavior
            };

            var serviceSettings = ActiveDirectoryServiceSettings.Azure;

            serviceSettings.TokenAudience = tokenAudience;

            var creds = UserTokenProvider.LoginWithPromptAsync(domain, clientSettings, serviceSettings, tokenCache).GetAwaiter().GetResult();

            return(creds);
        }
Exemplo n.º 15
0
        private static void LoginWithPromptAsync(
            Dictionary <TokenAudience, TokenCredentials> tokens,
            string domain,
            TestEndpoints endpoints)
        {
            var mgmSettings = new ActiveDirectoryServiceSettings()
            {
                AuthenticationEndpoint = new Uri(endpoints.AADAuthUri.ToString() + domain),
                TokenAudience          = endpoints.AADTokenAudienceUri
            };
            var grpSettings = new ActiveDirectoryServiceSettings()
            {
                AuthenticationEndpoint = new Uri(endpoints.AADAuthUri.ToString() + domain),
                TokenAudience          = endpoints.GraphTokenAudienceUri
            };

            var clientSettings = new ActiveDirectoryClientSettings()
            {
                ClientId          = TestEnvironment.ClientIdDefault,
                ClientRedirectUri = new Uri("urn:ietf:wg:oauth:2.0:oob"),
                PromptBehavior    = PromptBehavior.Auto
            };

            var mgmAuthResult = (TokenCredentials)UserTokenProvider
                                .LoginWithPromptAsync(domain, clientSettings, mgmSettings)
                                .ConfigureAwait(false)
                                .GetAwaiter().GetResult();

            try
            {
                var graphAuthResult = (TokenCredentials)UserTokenProvider
                                      .LoginWithPromptAsync(domain, clientSettings, grpSettings)
                                      .GetAwaiter().GetResult();
                tokens[TokenAudience.Graph] = graphAuthResult;
            }
            catch
            {
                // Not all accounts are registered to have access to Graph endpoints.
            }
            tokens[TokenAudience.Management] = mgmAuthResult;
        }
        public void UserCredentialsPopsDialog()
        {
            var cache       = new TestTokenCache();
            var settings    = ActiveDirectoryServiceSettings.Azure;
            var credentials = UserTokenProvider.LoginWithPromptAsync(this._domain,
                                                                     ActiveDirectoryClientSettings.UsePromptOnly("1950a258-227b-4e31-a9cf-717495945fc2", new Uri("urn:ietf:wg:oauth:2.0:oob")),
                                                                     settings, this._username, cache).GetAwaiter().GetResult();
            var client = new HttpClient();

            var request = new HttpRequestMessage(HttpMethod.Get,
                                                 new Uri("https://management.azure.com/subscriptions?api-version=2014-04-01-preview"));

            credentials.ProcessHttpRequestAsync(request, CancellationToken.None).Wait();
            Assert.NotNull(request.Headers.Authorization);
            var response = client.SendAsync(request).ConfigureAwait(false).GetAwaiter().GetResult();

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            // Repeat with PromptBehavior.Never
            credentials = UserTokenProvider.LoginWithPromptAsync(this._domain,
                                                                 ActiveDirectoryClientSettings.UseCacheOrCookiesOnly("1950a258-227b-4e31-a9cf-717495945fc2", new Uri("urn:ietf:wg:oauth:2.0:oob")),
                                                                 settings, this._username, cache).GetAwaiter().GetResult();
            request = new HttpRequestMessage(HttpMethod.Get,
                                             new Uri("https://management.azure.com/subscriptions?api-version=2014-04-01-preview"));
            credentials.ProcessHttpRequestAsync(request, CancellationToken.None).Wait();
            Assert.NotNull(request.Headers.Authorization);
            response = client.SendAsync(request).ConfigureAwait(false).GetAwaiter().GetResult();
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            // Repeat with getting tokens strictly from cache
            credentials = UserTokenProvider.CreateCredentialsFromCache("1950a258-227b-4e31-a9cf-717495945fc2", this._domain, this._username, cache).GetAwaiter().GetResult();
            request     = new HttpRequestMessage(HttpMethod.Get,
                                                 new Uri("https://management.azure.com/subscriptions?api-version=2014-04-01-preview"));
            credentials.ProcessHttpRequestAsync(request, CancellationToken.None).Wait();
            Assert.NotNull(request.Headers.Authorization);
            response = client.SendAsync(request).ConfigureAwait(false).GetAwaiter().GetResult();
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
        public void CredentialsConstructorThrowsForInvalidValues()
        {
            TokenCache cache    = new TestTokenCache();
            var        settings = ActiveDirectoryServiceSettings.Azure;

            Assert.ThrowsAsync <ArgumentOutOfRangeException>(() => UserTokenProvider.LoginSilentAsync(null,
                                                                                                      "microsoft.onmicrosoft.com", this._username, this._password, cache));
            Assert.ThrowsAsync <ArgumentOutOfRangeException>(() => UserTokenProvider.LoginWithPromptAsync(
                                                                 "microsoft.onmicrosoft.com", ActiveDirectoryClientSettings.UsePromptOnly(string.Empty, new Uri("urn:ietf:wg:oauth:2.0:oob")),
                                                                 settings, cache));
            Assert.ThrowsAsync <ArgumentOutOfRangeException>(() => UserTokenProvider.LoginWithPromptAsync(null,
                                                                                                          ActiveDirectoryClientSettings.UsePromptOnly("1950a258-227b-4e31-a9cf-717495945fc2", new Uri("urn:ietf:wg:oauth:2.0:oob")),
                                                                                                          settings, cache));
            Assert.ThrowsAsync <ArgumentOutOfRangeException>(() => UserTokenProvider.LoginWithPromptAsync(string.Empty,
                                                                                                          ActiveDirectoryClientSettings.UsePromptOnly("1950a258-227b-4e31-a9cf-717495945fc2", new Uri("urn:ietf:wg:oauth:2.0:oob")),
                                                                                                          settings, cache));
            Assert.ThrowsAsync <AuthenticationException>(() => UserTokenProvider.LoginSilentAsync("1950a258-227b-4e31-a9cf-717495945fc2",
                                                                                                  "microsoft.onmicrosoft.com", null, this._password, cache));
            Assert.Throws <AuthenticationException>(() => UserTokenProvider.LoginSilentAsync("1950a258-227b-4e31-a9cf-717495945fc2",
                                                                                             "microsoft.onmicrosoft.com", string.Empty, this._password, cache).ConfigureAwait(false).GetAwaiter().GetResult());
            Assert.ThrowsAsync <AuthenticationException>(() => UserTokenProvider.LoginSilentAsync("1950a258-227b-4e31-a9cf-717495945fc2",
                                                                                                  "microsoft.onmicrosoft.com", this._username, null, cache));
            Assert.ThrowsAsync <AuthenticationException>(() => UserTokenProvider.LoginSilentAsync("1950a258-227b-4e31-a9cf-717495945fc2",
                                                                                                  "microsoft.onmicrosoft.com", this._username, string.Empty, cache));
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            var resourceGroupName = "your resource group name of iot hub";
            var iothubName        = "your iot hub name";
            var tenantId          = "your tenant";
            var subscriptionId    = "your subscription";

            #region for native client, based on user login
            var nativeClientId    = "your native client id";
            var redirectUri       = "your native client redirect uri";
            var adServiceSettings = new ActiveDirectoryServiceSettings
            {
                AuthenticationEndpoint = new Uri(AzureEnvironment.AzureChinaCloud.AuthenticationEndpoint),
                TokenAudience          = new Uri(AzureEnvironment.AzureChinaCloud.ResourceManagerEndpoint),
                ValidateAuthority      = true
            };
            var adClientSettings = new ActiveDirectoryClientSettings()
            {
                ClientId          = nativeClientId,
                ClientRedirectUri = new Uri(redirectUri)
            };
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            ServiceClientCredentials azureCredential = null;
            try
            {
                azureCredential = UserTokenProvider.LoginWithPromptAsync(tenantId, adClientSettings, adServiceSettings).Result;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Acquire credential failed: {ex.Message}");
            }
            #endregion

            #region for web client, based on clientid and clientsecret
            //var webClientId = "your web client id";
            //azureCredential = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
            //        webClientId,
            //        "!!123abc",
            //        tenantId,
            //        AzureEnvironment.AzureChinaCloud);
            #endregion

            if (azureCredential != null)
            {
                var iothubClient = new IotHubClient(new Uri("https://management.chinacloudapi.cn/"), azureCredential, new RetryDelegatingHandler());
                iothubClient.SubscriptionId = subscriptionId;

                var iothubResource = iothubClient.IotHubResource;

                // get iothub description
                var iothubDescription = iothubResource.Get(resourceGroupName, iothubName);
                Console.WriteLine($"Get iothub successfully: {iothubDescription.Name}");

                // set C2D message default ttl to 2 hours
                iothubDescription.Properties.CloudToDevice.DefaultTtlAsIso8601 = TimeSpan.FromHours(2);

                try
                {
                    // commit the change
                    iothubResource.CreateOrUpdate(resourceGroupName, iothubName, iothubDescription);
                    Console.WriteLine("Update iothub successfully!");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Update iothub failed: {ex.Message}");
                }
            }

            Console.WriteLine("Press ENTER to exit!");
            Console.ReadLine();
        }
Exemplo n.º 19
0
 /// <summary>
 /// Log in to Azure active directory with credentials provided by the user.  This call may display a credentials
 /// dialog, depending on the supplied client settings and the state of the token cache and user cookies.
 /// </summary>
 /// <param name="domain">The domain to authenticate against.</param>
 /// <param name="clientSettings">The client settings to use for authentication. These determine when a dialog will be displayed.</param>
 /// <param name="serviceSettings">The settings for ad service, including endpoint and token audience</param>
 /// <param name="userId">The userid of the desired credentials</param>
 /// <param name="cache">The token cache to target during authentication.</param>
 /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the given credentials.</returns>
 public static async Task <ServiceClientCredentials> LoginWithPromptAsync(string domain, ActiveDirectoryClientSettings clientSettings,
                                                                          ActiveDirectoryServiceSettings serviceSettings, UserIdentifier userId, TokenCache cache)
 {
     return(await LoginWithPromptAsync(domain, clientSettings, serviceSettings, userId, cache, () => { return TaskScheduler.FromCurrentSynchronizationContext(); }));
 }
Exemplo n.º 20
0
        /// <summary>
        /// Log in to Azure active directory with credentials provided by the user.  This call may display a credentials
        /// dialog, depending on the supplied client settings and the state of the token cache and user cookies.
        /// </summary>
        /// <param name="domain">The domain to authenticate against.</param>
        /// <param name="clientSettings">The client settings to use for authentication. These determine when a dialog will be displayed.</param>
        /// <param name="serviceSettings">The settings for ad service, including endpoint and token audience</param>
        /// <param name="userId">The userid of the desired credentials</param>
        /// <param name="cache">The token cache to target during authentication.</param>
        /// <param name="taskScheduler">Scheduler needed to run the task</param>
        /// <returns></returns>
        public static async Task <ServiceClientCredentials> LoginWithPromptAsync(string domain, ActiveDirectoryClientSettings clientSettings,
                                                                                 ActiveDirectoryServiceSettings serviceSettings, UserIdentifier userId, TokenCache cache, Func <TaskScheduler> taskScheduler)
        {
            var authenticationContext = GetAuthenticationContext(domain, serviceSettings, cache);

            AuthenticationResult authResult;

            try
            {
                authResult = await authenticationContext.AcquireTokenAsync(
                    serviceSettings.TokenAudience.OriginalString,
                    clientSettings.ClientId,
                    clientSettings.ClientRedirectUri,
                    new PlatformParameters(clientSettings.PromptBehavior),
                    userId,
                    clientSettings.AdditionalQueryParameters);
            }
            catch (Exception e)
            {
                throw new AuthenticationException(
                          string.Format(CultureInfo.CurrentCulture, "Authentication error while acquiring token: '{0}'", e.Message), e);
            }

            var newUserId = new UserIdentifier(authResult.UserInfo.DisplayableId, UserIdentifierType.RequiredDisplayableId);

            return(new TokenCredentials(
                       new KvTokenProvider(authenticationContext, clientSettings.ClientId, serviceSettings.TokenAudience, newUserId),
                       authResult.TenantId,
                       authResult.UserInfo.DisplayableId));
        }