示例#1
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);
        }
示例#2
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);
            }
        }
        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));
        }
示例#4
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);
        }
        public static ServiceClientCredentials GetCredentialFromPrompt(TokenCache tokenCache)
        {
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

            // might need to specify the username as the 4th param if you need to switch user instead of the cached one
            //return UserTokenProvider.LoginWithPromptAsync(DomainOrTenantId, GetCredentialFromPromptClientSettings, ServiceSettings).GetAwaiter().GetResult();
            return(UserTokenProvider.LoginWithPromptAsync(DomainOrTenantId, GetCredentialFromPromptClientSettings, ServiceSettings, tokenCache).GetAwaiter().GetResult());
        }
示例#6
0
        public void InteractiveUserLogin(string cnnStr)
        {
            LiteralCnnString = cnnStr;
            ServiceClientCredentials svcClientCred = null;

            svcClientCred = UserTokenProvider.LoginWithPromptAsync(this.TenantId, GetADClientSettings(),
                                                                   ActiveDirectoryServiceSettings.AzureGermany,
                                                                   () => { return(TaskScheduler.FromCurrentSynchronizationContext()); }).GetAwaiter().GetResult();
            Assert.NotNull(svcClientCred);
        }
示例#7
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);
        }
示例#8
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);
        }
示例#9
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);
        }
示例#11
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
        }
示例#12
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();
        }