Exemplo n.º 1
0
        public override void CreateAuthorizationFile(string answerPath, string fileContents)
        {
            if (_DnsClient != null)
            {
                throw new InvalidOperationException($"Old authorization is still pending. Call {nameof(DeleteAuthorization)}() first!");
            }

            var url = new UrlElements(answerPath);

            if (String.IsNullOrWhiteSpace(Program.Options.AzureTenantId))
            {
                Program.Options.AzureTenantId = RequestViaCommandLine("Enter Azure Tenant ID: ");
            }

            if (String.IsNullOrWhiteSpace(Program.Options.AzureClientId))
            {
                Program.Options.AzureClientId = RequestViaCommandLine("Enter Azure Client ID: ");
            }

            if (String.IsNullOrWhiteSpace(Program.Options.AzureSecret))
            {
                Program.Options.AzureSecret = RequestViaCommandLine("Enter Azure Secret: ");
            }

            if (String.IsNullOrWhiteSpace(Program.Options.AzureSubscriptionId))
            {
                Program.Options.AzureSubscriptionId = RequestViaCommandLine("Enter Azure DNS Subscription ID: ");
            }

            if (String.IsNullOrWhiteSpace(Program.Options.AzureResourceGroupName))
            {
                Program.Options.AzureResourceGroupName = RequestViaCommandLine("Enter Azure DNS Resoure Group Name: ");
            }

            // Build the service credentials and DNS management client
            var serviceCreds = ApplicationTokenProvider.LoginSilentAsync(Program.Options.AzureTenantId, Program.Options.AzureClientId, Program.Options.AzureSecret).Result;

            _DnsClient = new DnsManagementClient(serviceCreds)
            {
                SubscriptionId = Program.Options.AzureSubscriptionId
            };

            // Create record set parameters
            var recordSetParams = new RecordSet();

            recordSetParams.TTL = 3600;

            // Add records to the record set parameter object.  In this case, we'll add a record of type 'TXT'
            recordSetParams.TxtRecords = new List <TxtRecord>();
            recordSetParams.TxtRecords.Add(new TxtRecord(new[] { fileContents }));

            // Create the actual record set in Azure DNS
            // Note: no ETAG checks specified, will overwrite existing record set if one exists
            var recordSet = _DnsClient.RecordSets.CreateOrUpdate(Program.Options.AzureResourceGroupName, url.Domain, url.Subdomain, RecordType.TXT, recordSetParams);
        }
Exemplo n.º 2
0
        static async Task Main(string[] args)
        {
            var resourceId = $"/subscriptions/{DefaultSubscription}/resourceGroups/XXX";

            var credentials = await ApplicationTokenProvider.LoginSilentAsync(
                TenantDomain,
                ClientId,
                ClientSecret);

            using (var client = new ResourceManagementClient(credentials))
            {
                client.SubscriptionId = DefaultSubscription;

                try
                {
                    // Create Predefined Tag name and value. Predefined Tags are not automatically
                    // applied to existing or newly created sub resources.
                    // Requires contributor permission at subscription level
                    //var t = await client.Tags.CreateOrUpdateAsync("PredefinedTag1");
                    //await client.Tags.CreateOrUpdateValueAsync("PredefinedTag1", "DefaultValue");

                    // Tags operations, only require Tags Contributor
                    // 1. Create/Update Tags on subscription,
                    var tags = new TagsResource(
                        new Tags(
                            new Dictionary <string, string>
                    {
                        { "environment", DateTimeOffset.Now.ToString() },
                        { "department", DateTimeOffset.Now.ToString() },
                        { "PredefinedTag1", "override" }
                    }));
                    var result = await client.Tags.CreateOrUpdateAtScopeAsync(resourceId, tags);

                    // 2. Update Tags on resource
                    var patchTags = new TagsPatchResource(
                        "Merge", // Replace, Delete
                        new Tags(
                            new Dictionary <string, string>
                    {
                        { "environment", DateTimeOffset.Now.ToString() },
                        { "department", DateTimeOffset.Now.ToString() },
                        { "newTag", DateTimeOffset.Now.ToString() },
                    }));

                    result = await client.Tags.UpdateAtScopeAsync(resourceId, patchTags);

                    // 3. Delete all Tags on the resource
                    await client.Tags.DeleteAtScopeAsync(resourceId);
                }
                catch (Exception e)
                {
                    System.Console.WriteLine(e.Message);
                }
            }
        }
        public async override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var adSettings = new ActiveDirectoryServiceSettings
            {
                AuthenticationEndpoint = new Uri(Environment.AuthenticationEndpoint),
                TokenAudience          = new Uri(Environment.ManagementEnpoint),
                ValidateAuthority      = true
            };
            string url = request.RequestUri.ToString();

            if (url.StartsWith(Environment.GraphEndpoint, StringComparison.OrdinalIgnoreCase))
            {
                adSettings.TokenAudience = new Uri(Environment.GraphEndpoint);
            }

            if (!credentialsCache.ContainsKey(adSettings.TokenAudience))
            {
                if (servicePrincipalLoginInformation != null)
                {
                    if (servicePrincipalLoginInformation.ClientSecret != null)
                    {
                        credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync(
                            TenantId, servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.ClientSecret, adSettings, TokenCache.DefaultShared);
                    }
#if NET45
                    else if (servicePrincipalLoginInformation.X509Certificate != null)
                    {
                        credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync(
                            TenantId, new ClientAssertionCertificate(servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.X509Certificate), adSettings, TokenCache.DefaultShared);
                    }
#endif
                    else
                    {
                        credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync(
                            TenantId, servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.Certificate, servicePrincipalLoginInformation.CertificatePassword, TokenCache.DefaultShared);
                    }
                }
#if !PORTABLE
                else if (userLoginInformation != null)
                {
                    credentialsCache[adSettings.TokenAudience] = await UserTokenProvider.LoginSilentAsync(
                        userLoginInformation.ClientId, TenantId, userLoginInformation.UserName,
                        userLoginInformation.Password, adSettings, TokenCache.DefaultShared);
                }
#endif
#if PORTABLE
                else if (deviceCredentialInformation != null)
                {
                    credentialsCache[adSettings.TokenAudience] = await UserTokenProvider.LoginByDeviceCodeAsync(
                        deviceCredentialInformation.ClientId, TenantId, adSettings, TokenCache.DefaultShared, deviceCredentialInformation.DeviceCodeFlowHandler);
                }
#endif
            }
            await credentialsCache[adSettings.TokenAudience].ProcessHttpRequestAsync(request, cancellationToken);
        }
Exemplo n.º 4
0
        private static async Task <MonitorClient> AuthenticateWithReadOnlyClient(string tenantId, string clientId, string secret, string subscriptionId)
        {
            // Build the service credentials and Monitor client
            var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, secret);

            var monitorClient = new MonitorClient(serviceCreds);

            monitorClient.SubscriptionId = subscriptionId;

            return(monitorClient);
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            adlsAccountName = "shellpocadlsgen1";
            string[] ad = new string[]
            {
                "[dbo].[item_dim].csv",
                "[dbo].[location_dim].csv",
                "[dbo].[manufacturer_dim].csv",
                "[dbo].[Retail_Sales_Transaction_Data].csv",
                "[dbo].[retailer_dim].csv",
                "[dbo].[store_dim].csv"
            };
            string[] src = new string[]
            {
                "item.csv",
                "location.csv",
                "manufacturer.csv",
                "trans.csv",
                "retailer.csv",
                "store.csv"
            };
            subscriptionId = "45110a54-85eb-46b4-8f41-c5d80533039c";
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            var domain           = "happiestminds.onmicrosoft.com";
            var clientId         = "98e780fd-9707-4690-a51e-7a05698f3f1e";
            var clientSecret     = "k0kmlvC7soT3cuwnxYC/10G4lOFQuHt0wt3CIFDPrbM=";
            var clientCredential = new ClientCredential(clientId, clientSecret);
            var creds            = ApplicationTokenProvider.LoginSilentAsync(domain, clientCredential).Result;

            adlsClient                = new DataLakeStoreAccountManagementClient(creds);
            adlsFileSystemClient      = new DataLakeStoreFileSystemManagementClient(creds);
            adlsClient.SubscriptionId = subscriptionId;
            //string sourceFolderPath = @"D:\ADLS\";
            //string sourceFolderPath = @"\\192.168.56.1\adls\";
            string sourceFolderPath = @"\ADLS\";
            string y = DateTime.Now.ToString("yyyy");
            string m = DateTime.Now.ToString("MMMM");
            string d = DateTime.Now.ToString("dd");

            System.Console.WriteLine(y);
            System.Console.WriteLine(m);
            System.Console.WriteLine(d);
            //string dataLakeStoreFolderPath = "/Development/"+y+"/"+m+"/"+d+"/";
            string dataLakeStoreFolderPath = "/Development/" + y + "/" + m + "/10/";

            for (int i = 0; i < 6; i++)
            {
                string sourceFilePath        = Path.Combine(sourceFolderPath, src[i]);
                string dataLakeStoreFilePath = Path.Combine(dataLakeStoreFolderPath, ad[i]);
                //adlsFileSystemClient.FileSystem.UploadFile(adlsAccountName, sourceFilePath, dataLakeStoreFilePath, 1, false, true);
                adlsFileSystemClient.FileSystem.DownloadFile(adlsAccountName, dataLakeStoreFilePath, sourceFilePath, 1, false, true);
            }
            Console.WriteLine("6. Finished!");
        }
Exemplo n.º 6
0
        /// <summary>
        /// Setsup the super client and returns
        /// </summary>
        /// <returns></returns>
        private static AdlsClient SetupSuperClient()
        {
            string clientId                      = SdkUnitTest.ReadSetting("AccountOwnerClientId");
            string clientSecret                  = SdkUnitTest.ReadSetting("AccountOwnerClientSecret");
            string domain                        = SdkUnitTest.ReadSetting("Domain");
            string clientAccountPath             = SdkUnitTest.ReadSetting("Account");
            var    creds                         = new ClientCredential(clientId, clientSecret);
            ServiceClientCredentials clientCreds = ApplicationTokenProvider.LoginSilentAsync(domain, creds).GetAwaiter().GetResult();

            return(AdlsClient.CreateClient(clientAccountPath, clientCreds));
        }
Exemplo n.º 7
0
        public async Task <MonitorClient> GetMonitorClient()
        {
            var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(Default.TenantId, Default.ClientId, Default.Secret);

            var monitorClient = new MonitorClient(serviceCreds)
            {
                SubscriptionId = Default.SubscriptionId
            };

            return(monitorClient);
        }
Exemplo n.º 8
0
        private async Task <MonitorClient> authenticate(string tenantId, string clientId, string secret, string subscriptionId)
        {
            var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, secret);

            var monitorClient = new MonitorClient(serviceCreds)
            {
                SubscriptionId = subscriptionId
            };

            return(monitorClient);
        }
        /// <summary>
        /// Creates credentials for the Azure Media Service based on credentials from Configuration (appsettings.json)
        /// </summary>
        /// <returns>Generic asynchronous operation that returns type ServiceClientCredentials</returns>

        private static async Task <ServiceClientCredentials> ClientCredentials()
        {
            if (_clientCredential == null)
            {
                _clientCredential = new ClientCredential(_configuration.AadClientId, _configuration.AadSecret);
            }

            return(await
                   ApplicationTokenProvider
                   .LoginSilentAsync(_configuration.AadTenantId, _clientCredential, ActiveDirectoryServiceSettings.Azure));
        }
        // </RunAsync>

        /// <summary>
        /// Create the ServiceClientCredentials object based on the credentials
        /// supplied in local configuration file.
        /// </summary>
        /// <param name="config">The parm is of type ConfigWrapper. This class reads values from local configuration file.</param>
        /// <returns></returns>
        // <GetCredentialsAsync>
        private static async Task <ServiceClientCredentials> GetCredentialsAsync(ConfigWrapper config)
        {
            // Use ApplicationTokenProvider.LoginSilentWithCertificateAsync or UserTokenProvider.LoginSilentAsync to get a token using service principal with certificate
            //// ClientAssertionCertificate
            //// ApplicationTokenProvider.LoginSilentWithCertificateAsync

            // Use ApplicationTokenProvider.LoginSilentAsync to get a token using a service principal with symetric key
            ClientCredential clientCredential = new ClientCredential(config.AadClientId, config.AadSecret);

            return(await ApplicationTokenProvider.LoginSilentAsync(config.AadTenantId, clientCredential, ActiveDirectoryServiceSettings.Azure));
        }
        private static async Task <IAzureMediaServicesClient> InitializeAmsClient(ServicePrincipalAuth spAuth)
        {
            ClientCredential clientCredential = new ClientCredential(spAuth.AadClientId, spAuth.AadSecret);

            ServiceClientCredentials serviceCredential = await ApplicationTokenProvider.LoginSilentAsync(spAuth.AadTenantId, clientCredential, Helpers.GetActiveDirectoryServiceSettings(spAuth.AADSettings));

            return(new AzureMediaServicesClient(spAuth.ArmEndpoint, serviceCredential)
            {
                SubscriptionId = spAuth.SubscriptionId
            });
        }
        static AzureMediaServicesClient GetV3Client(ConfigWrapper config)
        {
            ClientCredential clientCredential = new ClientCredential(config.AadClientId, config.AadSecret);
            var credentials = ApplicationTokenProvider.LoginSilentAsync(config.AadTenantId, clientCredential, ActiveDirectoryServiceSettings.Azure).Result;

            AzureMediaServicesClient v3Client = new AzureMediaServicesClient(config.ArmEndpoint, credentials)
            {
                SubscriptionId = config.SubscriptionId,
            };

            return(v3Client);
        }
        public static ServiceClientCredentials GetCredentialFromCertificate(string clientId, X509Certificate2 cert)
        {
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

#if net452
            return(ApplicationTokenProvider.LoginSilentWithCertificateAsync(DomainOrTenantId, new ClientAssertionCertificate(clientId, cert), ServiceSettings).GetAwaiter().GetResult());
#endif

#if !net452
            return(ApplicationTokenProvider.LoginSilentWithCertificateAsync(DomainOrTenantId, new Microsoft.Rest.Azure.Authentication.ClientAssertionCertificate(clientId, cert), ServiceSettings).GetAwaiter().GetResult());
#endif
        }
Exemplo n.º 14
0
        public async Task UpdateDns(CancellationToken cancellationToken)
        {
            var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(_securityConfig.TenantId, _securityConfig.ClientId, _securityConfig.ClientSecret);

            var dnsClient = new DnsManagementClient(serviceCreds)
            {
                SubscriptionId = _securityConfig.SubscriptionId
            };

            var currentIp = await _ipAddressLookup.GetCurrentIdAsync(cancellationToken);

            foreach (var recordSetName in _dnsConfig.RecordSetNames)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    _logger.LogInformation("Cancellation requested, aborting update");
                    return;
                }

                _logger.LogInformation($"Trying to update: {recordSetName}");

                try
                {
                    var recordSet = dnsClient.RecordSets.Get(_dnsConfig.ResourceGroupName, _dnsConfig.ZoneName, recordSetName, RecordType.A);

                    // Add a new record to the local object.  Note that records in a record set must be unique/distinct

                    // first we check if we need to update - no need to do it all the time
                    var currentARecord = recordSet.ARecords.FirstOrDefault();
                    if (currentARecord != null)
                    {
                        if (currentARecord.Ipv4Address.Equals(currentIp))
                        {
                            _logger.LogInformation("Current IP already set, trying next recordset.");
                            continue;
                        }
                    }

                    recordSet.ARecords.Clear();
                    recordSet.ARecords.Add(new ARecord(currentIp));

                    // Update the record set in Azure DNS
                    // Note: ETAG check specified, update will be rejected if the record set has changed in the meantime
                    recordSet = await dnsClient.RecordSets.CreateOrUpdateAsync(_dnsConfig.ResourceGroupName, _dnsConfig.ZoneName, recordSetName, RecordType.A, recordSet, recordSet.Etag, cancellationToken : cancellationToken);

                    _logger.LogInformation($"Success - {recordSetName}");
                }
                catch (System.Exception e)
                {
                    _logger.LogError(e, $"Failed - {recordSetName}");
                }
            }
        }
        private AzureMediaServicesClient GetAzureMediaServicesClient()
        {
            var clientCredential =
                new ClientCredential(_clientSettings?.AadClientId, _clientSettings?.AadSecret);
            var serviceClientCredentials = ApplicationTokenProvider.LoginSilentAsync(_clientSettings?.AadTenantId,
                                                                                     clientCredential, ActiveDirectoryServiceSettings.Azure).Result;

            return(new AzureMediaServicesClient(_clientSettings?.ArmEndpoint, serviceClientCredentials)
            {
                SubscriptionId = _clientSettings?.SubscriptionId
            });
        }
Exemplo n.º 16
0
        private static ServiceClientCredentials GetCredsServicePrincipalSecretKey(string domain, Uri tokenAudience, string clientId, string secretKey)
        {
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

            var serviceSettings = ActiveDirectoryServiceSettings.Azure;

            serviceSettings.TokenAudience = tokenAudience;

            var creds = ApplicationTokenProvider.LoginSilentAsync(domain, clientId, secretKey, serviceSettings).GetAwaiter().GetResult();

            return(creds);
        }
        public ArmApi(string oid, HttpControllerContext ctx)
        {
            var task = Task.Run(async() => {
                //_token was used for delegated user auth
                //_token = await AdalLib.GetAccessToken(oid, ctx, "https://management.azure.com");
                // Build the service credentials and DNS management client
                _serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(Settings.LabAdminTenantId, Settings.LabAdminClientId, Settings.LabAdminSecret);
                _isInit       = true;
            });

            task.Wait();
        }
Exemplo n.º 18
0
        private async Task <ServiceClientCredentials> GetCredentialsAsync()
        {
            // Use ApplicationTokenProvider.LoginSilentAsync to get a token using a service principal with symmetric key
            var clientCredential = new ClientCredential(
                _amsSettings.AadClientId,
                _amsSettings.AadSecret);

            return(await ApplicationTokenProvider.LoginSilentAsync(
                       _amsSettings.AadTenantId,
                       clientCredential,
                       ActiveDirectoryServiceSettings.Azure));
        }
Exemplo n.º 19
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            string ip = req.GetQueryParameterDictionary()
                        .FirstOrDefault(q => string.Compare(q.Key, "ip", true) == 0)
                        .Value;

            IPAddress ipAddress;

            if (ip == null || !IPAddress.TryParse(ip, out ipAddress))
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            log.LogInformation("IP update request received: " + ip);

            // Build the service credentials and DNS management client
            var tenantId          = Environment.GetEnvironmentVariable("TenantId");
            var clientId          = Environment.GetEnvironmentVariable("AppId");
            var secret            = Environment.GetEnvironmentVariable("AppSecret");
            var subscriptionId    = Environment.GetEnvironmentVariable("SubscriptionId");
            var resourceGroupName = Environment.GetEnvironmentVariable("ResourceGroupName");
            var zoneName          = Environment.GetEnvironmentVariable("ZoneName");
            var recordSetName     = Environment.GetEnvironmentVariable("RecordSetName");

            var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, secret);

            var dnsClient = new DnsManagementClient(serviceCreds);

            dnsClient.SubscriptionId = subscriptionId;

            var recordSet = dnsClient.RecordSets.Get(resourceGroupName, zoneName, recordSetName, RecordType.A);

            // Add a new record to the local object.  Note that records in a record set must be unique/distinct
            var currentIp = recordSet.ARecords[0].Ipv4Address;

            if (currentIp != ip)
            {
                recordSet.ARecords[0].Ipv4Address = ip;

                // Update the record set in Azure DNS
                // Note: ETAG check specified, update will be rejected if the record set has changed in the meantime
                recordSet = await dnsClient.RecordSets.CreateOrUpdateAsync(resourceGroupName, zoneName, recordSetName, RecordType.A, recordSet, recordSet.Etag);

                log.LogInformation("IP changed from " + currentIp + " to " + ip);

                return(new HttpResponseMessage(HttpStatusCode.OK));
            }

            return(new HttpResponseMessage(HttpStatusCode.Accepted));
        }
        public static async Task <AzureMediaServicesClient> GetClientAsync(ConfigurationModel config)
        {
            ClientCredential         clientCredentials = new ClientCredential(config.ClientId, config.ClientSecret);
            ServiceClientCredentials appCredentials    = await ApplicationTokenProvider.LoginSilentAsync(config.TenantId, clientCredentials, ActiveDirectoryServiceSettings.Azure);

            AzureMediaServicesClient client = new AzureMediaServicesClient(config.ManagementEndpoint, appCredentials)
            {
                SubscriptionId = config.SubscriptionId,
            };

            LoggerService.Info("Created authorization client", LoggerService.Bootstrapping);
            return(client);
        }
        /// <summary>
        /// Returns a task representing the attempt to log in to Azure public as the specified
        /// service principal, with the specified credential.
        /// </summary>
        /// <param name="certificateThumbprint"></param>
        /// <returns></returns>
        public static Task <ServiceClientCredentials> GetServiceCredentialsAsync(string tenantId, string applicationId, string appSecret)
        {
            if (_servicePrincipalCredential == null)
            {
                _servicePrincipalCredential = new ClientCredential(applicationId, appSecret);
            }

            return(ApplicationTokenProvider.LoginSilentAsync(
                       tenantId,
                       _servicePrincipalCredential,
                       ActiveDirectoryServiceSettings.Azure,
                       TokenCache.DefaultShared));
        }
Exemplo n.º 22
0
        public Azure(Target target, AzureOptions options, DomainParser domainParser, ILookupClientProvider lookupClientProvider, ILogService log, string identifier) : base(domainParser, lookupClientProvider, log, options, identifier)
        {
            // Build the service credentials and DNS management client
            var serviceCreds = ApplicationTokenProvider.LoginSilentAsync(
                _options.TenantId,
                _options.ClientId,
                _options.Secret).Result;

            _dnsClient = new DnsManagementClient(serviceCreds)
            {
                SubscriptionId = _options.SubscriptionId
            };
        }
Exemplo n.º 23
0
        public Azure(Target target)
        {
            // Build the service credentials and DNS management client
            var serviceCreds = ApplicationTokenProvider.LoginSilentAsync(
                target.DnsAzureOptions.TenantId,
                target.DnsAzureOptions.ClientId,
                target.DnsAzureOptions.Secret).Result;

            _DnsClient = new DnsManagementClient(serviceCreds)
            {
                SubscriptionId = target.DnsAzureOptions.SubscriptionId
            };
        }
Exemplo n.º 24
0
        private SecretKeyAdlsCredentials([Parameter(typeof(Tenant))] string tenant,
                                         [Parameter(typeof(TokenAudience))] string tokenAudience,
                                         [Parameter(typeof(ClientId))] string clientId,
                                         [Parameter(typeof(SecretKey))] string secretKey)
        {
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

            var serviceSettings = ActiveDirectoryServiceSettings.Azure;

            serviceSettings.TokenAudience = new Uri(tokenAudience);

            Credentials = ApplicationTokenProvider.LoginSilentAsync(tenant, clientId, secretKey, serviceSettings).Result;
        }
Exemplo n.º 25
0
        private static ServiceClientCredentials GetCredsServicePrincipalCertificate(string domain, Uri tokenAudience, string clientId, X509Certificate2 certificate)
        {
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

            var clientAssertionCertificate = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate(clientId, certificate);
            var serviceSettings            = ActiveDirectoryServiceSettings.Azure;

            serviceSettings.TokenAudience = tokenAudience;

            var creds = ApplicationTokenProvider.LoginSilentWithCertificateAsync(domain, clientAssertionCertificate, serviceSettings).GetAwaiter().GetResult();

            return(creds);
        }
Exemplo n.º 26
0
        internal MediaStorage(MediaAccount mediaAccount, MediaStorageAccount storageAccount) : base(storageAccount.Type, storageAccount.Id)
        {
            ServiceClientCredentials clientCredentials = ApplicationTokenProvider.LoginSilentAsync(mediaAccount.DirectoryTenantId, mediaAccount.ServicePrincipalId, mediaAccount.ServicePrincipalKey).Result;
            StorageManagementClient  storageClient     = new StorageManagementClient(clientCredentials)
            {
                SubscriptionId = mediaAccount.SubscriptionId
            };

            _storageAccountName = Path.GetFileName(storageAccount.Id);
            IEnumerable <StorageAccount> storageAccounts = storageClient.StorageAccounts.List();

            storageAccounts = storageAccounts.Where(s => s.Name.Equals(_storageAccountName, StringComparison.OrdinalIgnoreCase));
            _storageAccount = storageAccounts.SingleOrDefault();
        }
        private async Task CreateMediaServiceClient()
        {
            var clientCredential = new ClientCredential(aadClientId, aadSecret);

            var token = await ApplicationTokenProvider.LoginSilentAsync(
                aadTenantId,
                clientCredential,
                ActiveDirectoryServiceSettings.Azure);

            mediaServiceClient = new AzureMediaServicesClient(token)
            {
                SubscriptionId = subscriptionId
            };
        }
        public bool RunLAQuery(string tableName)
        {
            try
            {
                // Get credentials fron config.json
                var appConfig   = new AppConfig();
                var credentials = appConfig.GetCredentials();
                customerId   = credentials["workspaceId"];
                clientId     = credentials["clientId"];
                clientSecret = credentials["clientSecret"];
                domain       = credentials["domain"];

                var authEndpoint  = "https://login.microsoftonline.com";
                var tokenAudience = "https://api.loganalytics.io/";

                var adSettings = new ActiveDirectoryServiceSettings
                {
                    AuthenticationEndpoint = new Uri(authEndpoint),
                    TokenAudience          = new Uri(tokenAudience),
                    ValidateAuthority      = true
                };

                var creds = ApplicationTokenProvider.LoginSilentAsync(domain, clientId, clientSecret, adSettings).GetAwaiter().GetResult();

                var laClient = new OperationalInsightsDataClient(creds);
                laClient.WorkspaceId = customerId;

                var path    = new SampleDataPath();
                var dirPath = path.GetDirPath();
                tableName = tableName.Replace(dirPath, "").Replace(".json", "");

                string query = tableName
                               + @"| where TimeGenerated > ago(10d)
                             | limit 100";
                var results    = laClient.Query(query);
                var tableCount = results.Tables.Count;
                if (tableCount > 0)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Calling Log Analytics Error " + ex.Message);
            }
        }
        public void ValidApplicationCredentialsAuthenticateCorrectly()
        {
            var cache       = new TestTokenCache();
            var credentials = ApplicationTokenProvider.LoginSilentAsync(this._domain, this._applicationId, this._secret, 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);
        }
Exemplo n.º 30
0
        private async Task <ServiceClientCredentials> GetCredentialsAsync()
        {
            // Use ApplicationTokenProvider.LoginSilentWithCertificateAsync or UserTokenProvider.LoginSilentAsync to get a token using service principal with certificate
            //// ClientAssertionCertificate
            //// ApplicationTokenProvider.LoginSilentWithCertificateAsync

            // Use ApplicationTokenProvider.LoginSilentAsync to get a token using a service principal with symmetric key
            var aadClientId     = "ff79ecc9-27de-43ef-91ac-f0daf5263db6";
            var aadClientSecret = "8i2o07Zzl0MRgjov-M6mc.q9i~_ogAsa19";
            ClientCredential clientCredential = new ClientCredential(aadClientId, aadClientSecret);
            var aadTenantId = "1d9ed556-b09d-48f2-a5ba-173b21b5fea8";

            return(await ApplicationTokenProvider.LoginSilentAsync(aadTenantId, clientCredential, ActiveDirectoryServiceSettings.Azure));
        }