Exemplo n.º 1
0
        public async Task Update()
        {
            if (tenantId == null || clientId == null || secret == null || subscriptionId == null || resourceGroupName == null || zoneName == null || recordSetName == null)
            {
#pragma warning disable CA1303 // Do not pass literals as localized parameters
                _logger.LogError("Configuration settings not set.");
#pragma warning restore CA1303 // Do not pass literals as localized parameters
            }
            else
            {
                try
                {
                    using (_telemetryClient.StartOperation <RequestTelemetry>("operation"))
                    {
                        var ipAddress = await GetPublicIP().ConfigureAwait(true);

                        if (null != ipAddress)
                        {
                            // Build the service credentials and DNS management client
                            var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, secret).ConfigureAwait(true);

                            var dnsClient = new DnsManagementClient(serviceCreds);
                            dnsClient.SubscriptionId = subscriptionId;

                            var currentRecordSet = await dnsClient.RecordSets.GetAsync(resourceGroupName, zoneName, recordSetName, RecordType.A).ConfigureAwait(true);

                            if (currentRecordSet.ARecords.Where(r => r.Ipv4Address == ipAddress).Count() == 1)
                            {
                                _logger.LogInformation("Zone already up to date with IP: " + ipAddress);
                                _telemetryClient.TrackEvent("IP Address already up to date");
                            }
                            else
                            {
                                // Create record set parameters
                                var recordSetParams = new RecordSet();
                                recordSetParams.TTL = 300;

                                // Add records to the record set parameter object.
                                recordSetParams.ARecords = new List <ARecord>();
                                recordSetParams.ARecords.Add(new ARecord(ipAddress));

                                // Create the actual record set in Azure DNS
                                // Note: no ETAG checks specified, will overwrite existing record set if one exists
                                await dnsClient.RecordSets.CreateOrUpdateAsync(resourceGroupName, zoneName, recordSetName, RecordType.A, recordSetParams).ConfigureAwait(true);

                                _logger.LogInformation("Zone Updated with IP: " + ipAddress);
                                _telemetryClient.TrackEvent("Updated IP Address");
                            }

                            dnsClient.Dispose();
                        }
                    }
                }
                catch (Exception e)
                {
                    _logger.LogError(e.ToString());
                    _telemetryClient.TrackException(e);
                }
            }
        }
Exemplo n.º 2
0
        public async void DeployTemplate(string deploymentName, string resourceGroupName, string resourceGroupLocation,
                                         dynamic template, dynamic parameters)
        {
            // Try to obtain the service credentials
            var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(TenantId, ClientId, ClientSecret);

            // Create the resource manager client
            var resourceManagementClient = new ResourceManagementClient(serviceCreds);

            resourceManagementClient.SubscriptionId = SubscriptionId;

            // Create or check that resource group exists
            ensureResourceGroupExists(resourceManagementClient, resourceGroupName, resourceGroupLocation);

            // Start a deployment
            Console.WriteLine(string.Format("Starting template deployment '{0}' in resource group '{1}'", deploymentName, resourceGroupName));
            var deployment = new Deployment();

            deployment.Properties = new DeploymentProperties
            {
                Mode       = DeploymentMode.Incremental,
                Template   = template,
                Parameters = parameters
            };

            var deploymentResult = resourceManagementClient.Deployments.CreateOrUpdate(resourceGroupName, deploymentName, deployment);

            Console.WriteLine(string.Format("Deployment status: {0}", deploymentResult.Properties.ProvisioningState));
        }
Exemplo n.º 3
0
        public static void Run([ServiceBusTrigger("events", "data-lake", AccessRights.Listen, Connection = "ServiceBusConnectionString")] BrokeredMessage message, TraceWriter log)
        {
            var messageId   = message.MessageId;
            var messageBody = new StreamReader(message.GetBody <Stream>(), Encoding.UTF8);

            try
            {
                SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
                var clientCredential = new ClientCredential(servicePrincipalId, servicePrincipalKey);
                var creds            = ApplicationTokenProvider.LoginSilentAsync(domain, clientCredential).Result;

                var adlsFileSystemClient = new DataLakeStoreFileSystemManagementClient(creds);

                if (message.Properties["merge"].ToString() == "false")
                {
                    adlsFileSystemClient.FileSystem.ConcurrentAppend(adlAccountName, updateFilePath, messageBody.BaseStream, appendMode: AppendModeType.Autocreate);
                    log.Info($"The message has been sent to the data lake messageId: {messageId}", "DATA_LAKE_UPDATE");
                }
                else if (message.Properties["merge"].ToString() == "true")
                {
                    adlsFileSystemClient.FileSystem.ConcurrentAppend(adlAccountName, mergeFilePath, messageBody.BaseStream, appendMode: AppendModeType.Autocreate);
                    log.Info($"The message has been sent to the data lake messageId: {messageId}", "DATA_LAKE_(UN)MERGE");
                }
            }
            catch (Exception e)
            {
                log.Error("There was an error processing the message: ", e, "DATA_LAKE_ERROR");
            }
        }
Exemplo n.º 4
0
        private async Task <DnsManagementClient> GetClient()
        {
            if (_azureDnsClient == null)
            {
                // Build the service credentials and DNS management client
                ServiceClientCredentials credentials;

                // Decide between Managed Service Identity (MSI)
                // and service principal with client credentials
                if (_options.UseMsi)
                {
                    var azureServiceTokenProvider = new AzureServiceTokenProvider();
                    var accessToken = await azureServiceTokenProvider.GetAccessTokenAsync(_resourceManagerEndpoint.ToString());

                    credentials = new TokenCredentials(accessToken);
                }
                else
                {
                    credentials = await ApplicationTokenProvider.LoginSilentAsync(
                        _options.TenantId,
                        _options.ClientId,
                        _options.Secret.Value,
                        GetActiveDirectorySettingsForAzureEnvironment());
                }

                _azureDnsClient = new DnsManagementClient(credentials, _proxyService.GetHttpClient(), true)
                {
                    BaseUri        = _resourceManagerEndpoint,
                    SubscriptionId = _options.SubscriptionId
                };
            }
            return(_azureDnsClient);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Initializes a new instance of the DataBoxManagementClient class
        /// </summary>
        /// <returns></returns>
        static DataBoxManagementClient InitializeDataBoxClient()
        {
            const string frontDoorUrl = "https://login.microsoftonline.com";
            const string tokenUrl     = "https://management.azure.com";

            // Fetch the configuration parameters.
            tenantId          = CloudConfigurationManager.GetSetting("TenantId");
            subscriptionId    = CloudConfigurationManager.GetSetting("SubscriptionId");
            aadApplicationId  = CloudConfigurationManager.GetSetting("AADApplicationId");
            aadApplicationKey = CloudConfigurationManager.GetSetting("AADApplicationKey");

            // Validates AAD ApplicationId and returns token
            var credentials = ApplicationTokenProvider.LoginSilentAsync(
                tenantId,
                aadApplicationId,
                aadApplicationKey,
                new ActiveDirectoryServiceSettings()
            {
                AuthenticationEndpoint = new Uri(frontDoorUrl),
                TokenAudience          = new Uri(tokenUrl),
                ValidateAuthority      = true,
            }).GetAwaiter().GetResult();

            // Initializes a new instance of the DataBoxManagementClient class.
            DataBoxManagementClient dataBoxManagementClient = new DataBoxManagementClient(credentials);

            // Set SubscriptionId
            dataBoxManagementClient.SubscriptionId = subscriptionId;

            return(dataBoxManagementClient);
        }
Exemplo n.º 6
0
        private static async Task Initialize()
        {
            // Initialize the resource client with the service principal
            // credentials. Save the instance into a static variable for reuse.
            if (_resourceClient == null)
            {
                var tenantId       = System.Environment.GetEnvironmentVariable("TenantId");
                var clientId       = System.Environment.GetEnvironmentVariable("ClientId");
                var clientSecret   = System.Environment.GetEnvironmentVariable("ClientSecret");
                var subscriptionId = System.Environment.GetEnvironmentVariable("SubscriptionId");
                var serviceCreds   = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, clientSecret);

                _resourceClient = new ResourceManagementClient(serviceCreds)
                {
                    SubscriptionId = subscriptionId
                };
            }

            // Retrieve a list of providers for future reference. We'll
            // use these to look up API versions when querying the state
            // of a resource.
            if (_providers == null || _providers.Count == 0)
            {
                _providers = _resourceClient.Providers.List().ToList();
            }
        }
Exemplo n.º 7
0
        public AzureMediaProcessorTests(ITestOutputHelper testOutputHelper)
        {
            _testOutputHelper = testOutputHelper;
            var secret     = ".Xb2v7adwQwodK79p1FKe-75.F.nWp.4BY";
            var clientId   = "950c69c8-b022-4b93-8d47-0e452ad0567a";
            var tenantId   = "e08a9711-1bd0-47dd-8686-28c016518286";
            var credendial =
                ApplicationTokenProvider.LoginSilentAsync(tenantId, new ClientCredential(clientId, secret),
                                                          ActiveDirectoryServiceSettings.Azure).GetAwaiter()
                .GetResult();

            var armEndpoint = "https://management.azure.com";
            var client      = new AzureMediaServicesClient(new Uri(armEndpoint), credendial)
            {
                SubscriptionId = "c104684d-4609-4677-b322-c8e66e49c5f1"
            };

            var options = new AzureMediaProcessorOption()
            {
                AccountName           = "elnmedia",
                ResourceGroupName     = "everlearn",
                TransformName         = "EverlearnTransformWithAdaptiveStreamingPreset",
                StreamingEndpointName = "default",
                Issuer   = "https://everlearn.vn",
                Audience = "https://abc.com",
                TokenKey = Convert.FromBase64String(
                    "TFBMU3ZCNVJ1ekZ4cFZxRnhXc1VzQ0wyRDgzekxPRmxHVjBSOHJUcDFmK3hyUVRXWE8vWEFRPT0K")
            };

            _sut = new AzureMediaProcessor(client, options);

            _client  = client;
            _options = options;
        }
        private async Task <ServiceClientCredentials> getServiceClientCredentials(ConfigurationPackage config)
        {
            if (!config.Settings.Sections.Contains("ServicePrinciple"))
            {
                throw new ArgumentException(string.Format(ParameterCannotBeNullFormat, "ServicePrinciple"),
                                            "ServicePrinciple");
            }

            var servicePrinciple = config.Settings.Sections["ServicePrinciple"];

            if (!servicePrinciple.Parameters.Contains("Tenant"))
            {
                throw new ArgumentException(
                          string.Format(ParameterCannotBeNullFormat, "Tenant"),
                          "Tenant");
            }

            if (!servicePrinciple.Parameters.Contains("ObjectId"))
            {
                throw new ArgumentException(
                          string.Format(ParameterCannotBeNullFormat, "ObjectId"),
                          "ObjectId");
            }

            if (!servicePrinciple.Parameters.Contains("Secret"))
            {
                throw new ArgumentException(string.Format(ParameterCannotBeNullFormat, "Secret"),
                                            "Secret");
            }

            return(await ApplicationTokenProvider.LoginSilentAsync(servicePrinciple.Parameters["Tenant"].Value,
                                                                   new ClientCredential(servicePrinciple.Parameters["ObjectId"].Value,
                                                                                        servicePrinciple.Parameters["Secret"].Value)));
        }
Exemplo n.º 9
0
        private void InitializeADLS()
        {
            this.adlsAccountName = ConfigurationManager.AppSettings["adlsAccountName"];
            string subId            = ConfigurationManager.AppSettings["subId"];
            string remoteFolderPath = "/Hackfest/";

            remoteFileName = "test" + partitionID + ".txt";
            remoteFilePath = remoteFolderPath + remoteFileName;

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            var domain           = ConfigurationManager.AppSettings["domain"];
            var webApp_clientId  = ConfigurationManager.AppSettings["webApp_clientId"];
            var clientSecret     = ConfigurationManager.AppSettings["clientSecret"];
            var clientCredential = new ClientCredential(webApp_clientId, clientSecret);
            var creds            = ApplicationTokenProvider.LoginSilentAsync(domain, clientCredential).Result;

            adlsClient                = new DataLakeStoreAccountManagementClient(creds);
            adlsFileSystemClient      = new DataLakeStoreFileSystemManagementClient(creds);
            adlsClient.SubscriptionId = subId;

            //create directory if not already exist
            if (!adlsFileSystemClient.FileSystem.PathExists(adlsAccountName, remoteFolderPath))
            {
                adlsFileSystemClient.FileSystem.Mkdirs(adlsAccountName, remoteFolderPath);
            }
            //create/overwrite the file
            string header = "";
            var    stream = new MemoryStream(Encoding.UTF8.GetBytes(header));

            adlsFileSystemClient.FileSystem.Create(adlsAccountName, remoteFilePath, stream, true);
        }
Exemplo n.º 10
0
        public static async Task <BillingClient> GetBillingClient()
        {
            // Import config values from appsettings.json into billingClient, or throw an error if not found
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json");

            Configuration = builder.Build();

            var tenantId       = Configuration["TenantDomain"];
            var clientId       = Configuration["ClientID"];
            var secret         = Configuration["ClientSecret"];
            var subscriptionId = Configuration["SubscriptionID"];

            if (new List <string> {
                tenantId, clientId, secret, subscriptionId
            }.Any(i => String.IsNullOrEmpty(i)))
            {
                throw new InvalidOperationException("Enter TenantDomain, ClientID, ClientSecret and SubscriptionId in appsettings.json");
            }
            else
            {
                // Build the service credentials and ARM client to call the billing API
                var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, secret);

                var billingClient = new BillingClient(serviceCreds);
                billingClient.SubscriptionId = subscriptionId;
                return(billingClient);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Create the ServiceClientCredentials object based on the credentials
        /// supplied in local configuration file.
        /// </summary>
        /// <param name="config">The param is of type ConfigWrapper. This class reads values from local configuration file.</param>
        /// <returns></returns>
        private static async Task <ServiceClientCredentials> GetCredentialsAsync(ConfigWrapper config)
        {
            // Use ApplicationTokenProvider.LoginSilentAsync to get a token using a service principal with symmetric key
            ClientCredential clientCredential = new ClientCredential(config.AadClientId, config.AadSecret);

            return(await ApplicationTokenProvider.LoginSilentAsync(config.AadTenantId, clientCredential, ActiveDirectoryServiceSettings.Azure));
        }
Exemplo n.º 12
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function is processing a request.");

            var creds       = new ClientCredential(applicationId, clientSecret);
            var clientCreds = ApplicationTokenProvider.LoginSilentAsync(tenantId, creds).GetAwaiter().GetResult();

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            requestBody = requestBody.Replace(System.Environment.NewLine, " ");

            // Create ADLS client object
            AdlsClient client = AdlsClient.CreateClient(adlsAccountName, clientCreds);

            try
            {
                string fileName = "/yvr/YVR-test";

                if (!client.CheckExists(fileName))
                {
                    // Create a file - automatically creates any parent directories that don't exist
                    // The AdlsOutputStream preserves record boundaries - it does not break records while writing to the store
                    using (var stream = client.CreateFile(fileName, IfExists.Overwrite))
                    {
                        byte[] textByteArray = Encoding.UTF8.GetBytes(requestBody + "\r\n");
                        stream.Write(textByteArray, 0, textByteArray.Length);
                        Console.WriteLine("File Created, Data Appended. \n");
                        log.LogInformation("File Created, Data Appended. \n");
                    }
                }
                else
                {
                    // Append to existing file
                    using (var stream = client.GetAppendStream(fileName))
                    {
                        byte[] textByteArray = Encoding.UTF8.GetBytes(requestBody + "\r\n");
                        stream.Write(textByteArray, 0, textByteArray.Length);
                        Console.WriteLine("Data Appended. \n");
                        log.LogInformation("Data Appended. \n");
                    }
                }

                //Read file contents
                using (var readStream = new StreamReader(client.GetReadStream(fileName)))
                {
                    string line;
                    while ((line = readStream.ReadLine()) != null)
                    {
                        log.LogInformation(line);
                        Console.WriteLine(line);
                    }
                }
            }
            catch (AdlsException e)
            {
                PrintAdlsException(e);
            }

            return(new OkObjectResult("Success"));
        }
        public void CertificateTokenProviderRefreshWorks()
        {
            var thumbprint = "F064B7C7EACC942D10662A5115E047E94FA18498";

            System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates;
            Assert.True(TryFindCertificatesInStore(thumbprint, System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine, out certificates));

            var cache = new TestTokenCache();

            byte[] certificate = certificates[0].Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, _certificatePassword);
            var    credentials = ApplicationTokenProvider.LoginSilentAsync(
                "1449d5b7-8a83-47db-ae4c-9b03e888bad0",
                "20c58db7-4501-44e8-8e76-6febdb400c6b",
                certificate,
                _certificatePassword)
                                 .GetAwaiter().GetResult();

            cache.ForceTokenExpiry();
            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.º 14
0
        private async Task RunUSQLScriptFlowAsync()
        {
            var variables = new Dictionary <string, object>();

            var jobName = ConsoleEx.ReadLine("Job Name", "MyDlaJob");
            var path    = ConsoleEx.ReadLine("Path to U-SQL File", @"c:\tmp\job.usql", s => File.Exists(s));
            var script  = File.ReadAllText(path);

            Console.WriteLine("Parameters");

            while (true)
            {
                var name = ConsoleEx.ReadLine("Parameter <Blank to Continue>");
                if (string.IsNullOrWhiteSpace(name))
                {
                    break;
                }

                var val = ConsoleEx.ReadLine($"Value for @{name}");

                variables.Add(name, val);
            }

            // Authenticate against Azure AD once and re-use for all needed purposes
            var serviceClientCredentials = await ApplicationTokenProvider.LoginSilentAsync(
                Config.Root[Config.NAH_AAD_Domain],
                new ClientCredential(Config.Root[Config.NAH_AAD_CLIENTID], Config.Root[Config.NAH_AAD_CLIENTSECRET]));

            var jm = new DataLakeAnalyticsJobManager(serviceClientCredentials,
                                                     Config.Root[Config.NAH_AZURE_SUBSCRIPTIONID], Config.Root[Config.NAH_AZURE_DLA_ACCOUNTNAME]);
            var jobId = await jm.SubmitJobAsync(jobName, script, variables);

            await jm.WaitForJobAsync(jobId);
        }
Exemplo n.º 15
0
        public static async Task <string> GetOAuthTokenFromAAD()
        {
            var tenantId     = ConfigurationManager.AppSettings["tenantId"];
            var clientId     = ConfigurationManager.AppSettings["clientId"];
            var clientSecret = ConfigurationManager.AppSettings["clientSecret"];
            var adSettings   = new ActiveDirectoryServiceSettings
            {
                AuthenticationEndpoint = new Uri(AzureEnvironment.AzureGlobalCloud.AuthenticationEndpoint),
                TokenAudience          = new Uri(AzureEnvironment.AzureGlobalCloud.ManagementEndpoint),
                ValidateAuthority      = true
            };

            await ApplicationTokenProvider.LoginSilentAsync(
                tenantId,
                clientId,
                clientSecret,
                adSettings,
                TokenCache.DefaultShared);

            var token = TokenCache.DefaultShared.ReadItems()
                        .Where(t => t.ClientId == clientId)
                        .OrderByDescending(t => t.ExpiresOn)
                        .First();

            return(token.AccessToken);
        }
Exemplo n.º 16
0
        private async Task <AzureMediaServicesClient> GetClient()
        {
            AzureMediaServicesClient _client;

            if (_clients.ContainsKey(CREDENTIAL_NAME))
            {
                _client = _clients[CREDENTIAL_NAME];
            }
            else
            {
                var credential = _mediaCredential.Value;

                var clientCredential = new ClientCredential(
                    credential.AadClientId,
                    credential.AadSecret);

                var cred = await ApplicationTokenProvider.LoginSilentAsync(
                    credential.AadTenantId,
                    clientCredential,
                    ActiveDirectoryServiceSettings.Azure);

                var client = new AzureMediaServicesClient(credential.ArmEndpoint, cred)
                {
                    SubscriptionId = credential.SubscriptionId,
                };

                client.LongRunningOperationRetryTimeout = 30;

                _clients.Add(CREDENTIAL_NAME, client);
                _client = _clients[CREDENTIAL_NAME];
            }

            return(_client);
        }
        public void AuthExceptionWithNullInnerException()
        {
            AuthenticationException authExToBeThrown = null;
            string authError = "Error Occured";

            try
            {
                ClientCredential cc = new ClientCredential("SomeClientId", "SomethingSomething");
                ActiveDirectoryServiceSettings adSvcSettings = new ActiveDirectoryServiceSettings()
                {
                    AuthenticationEndpoint = new Uri("https://randomEndPoint"),
                    TokenAudience          = new Uri("https://SomeUri"),
                    ValidateAuthority      = true
                };

                var token = ApplicationTokenProvider.LoginSilentAsync("SomeDomain", cc, adSvcSettings).GetAwaiter().GetResult();
            }
            catch (AdalException adalEx)
            {
                authExToBeThrown = new AuthenticationException(authError);
            }

            Assert.NotNull(authExToBeThrown);
            Assert.Equal(authError, authExToBeThrown.Message);
        }
Exemplo n.º 18
0
        private async Task <DnsManagementClient> GetClient()
        {
            if (_azureDnsClient == null)
            {
                // Build the service credentials and DNS management client
                ServiceClientCredentials credentials;

                // Decide between Managed Service Identity (MSI) and service principal with client credentials
                if (_options.UseMsi)
                {
                    var azureServiceTokenProvider = new AzureServiceTokenProvider();
                    var accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/");

                    credentials = new TokenCredentials(accessToken);
                }
                else
                {
                    credentials = await ApplicationTokenProvider.LoginSilentAsync(
                        _options.TenantId,
                        _options.ClientId,
                        _options.Secret.Value);
                }

                _azureDnsClient = new DnsManagementClient(credentials, _proxyService.GetHttpClient(), true)
                {
                    SubscriptionId = _options.SubscriptionId
                };
            }
            return(_azureDnsClient);
        }
Exemplo n.º 19
0
        public async void Run(string subscriptionId,
                              string clientId,
                              string clientSecret,
                              string resourceGroupName,
                              string deploymentName,
                              string resourceGroupLocation, // must be specified for creating a new resource group
                              string pathToTemplateFile,
                              string pathToParameterFile,
                              string tenantId)
        {
            // Try to obtain the service credentials
            var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, clientSecret);

            // Read the template and parameter file contents
            JObject templateFileContents  = GetJsonFileContents(pathToTemplateFile);
            JObject parameterFileContents = GetJsonFileContents(pathToParameterFile);

            // Create the resource manager client
            var resourceManagementClient = new ResourceManagementClient(serviceCreds);

            resourceManagementClient.SubscriptionId = subscriptionId;

            // Create or check that resource group exists
            EnsureResourceGroupExists(resourceManagementClient, resourceGroupName, resourceGroupLocation);

            // Start a deployment
            DeployTemplate(resourceManagementClient, resourceGroupName, deploymentName, templateFileContents, parameterFileContents);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Acquire Graph token
        /// </summary>
        /// <param name="graphAADServiceSettings"></param>
        /// <param name="spnClientId"></param>
        /// <param name="spnSecret"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="psClientId"></param>
        private void UpdateTokenInfoWithGraphToken(ActiveDirectoryServiceSettings graphAADServiceSettings, string spnClientId = "", string spnSecret = "",
                                                   string userName = "", string password = "", string psClientId = "")
        {
            Task <TokenCredentials> graphAuthResult = null;

            try
            {
                if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
                {
                    //#if FullNetFx
#if net452
                    graphAuthResult = Task.Run(async() => (TokenCredentials)await UserTokenProvider
                                               .LoginSilentAsync(psClientId, this.Tenant, userName, password, graphAADServiceSettings).ConfigureAwait(continueOnCapturedContext: false));
#endif
                }
                else if (!string.IsNullOrWhiteSpace(spnClientId) && !string.IsNullOrWhiteSpace(spnSecret))
                {
                    graphAuthResult = Task.Run(async() => (TokenCredentials)await ApplicationTokenProvider
                                               .LoginSilentAsync(this.Tenant, spnClientId, spnSecret, graphAADServiceSettings).ConfigureAwait(continueOnCapturedContext: false));
                }

                this.TokenInfo[TokenAudience.Graph] = graphAuthResult?.Result;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("Error while acquiring Graph Token: '{0}'", ex.ToString()));
                // Not all accounts are registered to have access to Graph endpoints.
            }
        }
Exemplo n.º 21
0
        public async Task <bool> InitProvider(Dictionary <string, string> credentials, Dictionary <string, string> parameters, ILog log = null)
        {
            _log = log;

            _credentials = credentials;

            // https://docs.microsoft.com/en-us/dotnet/api/overview/azure/dns?view=azure-dotnet

            var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(
                _credentials["tenantid"],
                _credentials["clientid"],
                _credentials["secret"]
                );

            _dnsClient = new DnsManagementClient(serviceCreds);

            _dnsClient.SubscriptionId = _credentials["subscriptionid"];

            if (parameters?.ContainsKey("propagationdelay") == true)
            {
                if (int.TryParse(parameters["propagationdelay"], out int customPropDelay))
                {
                    _customPropagationDelay = customPropDelay;
                }
            }
            return(true);
        }
        public async override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var adSettings = new ActiveDirectoryServiceSettings
            {
                AuthenticationEndpoint = new Uri(Environment.AuthenticationEndpoint),
                TokenAudience          = new Uri(Environment.ManagementEndpoint),
                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, adSettings, 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
                else if (msiTokenProviderFactory != null)
                {
                    credentialsCache[adSettings.TokenAudience] = new TokenCredentials(this.msiTokenProviderFactory.Create(adSettings.TokenAudience.OriginalString));
                }
            }
            await credentialsCache[adSettings.TokenAudience].ProcessHttpRequestAsync(request, cancellationToken);
        }
Exemplo n.º 23
0
        public async Task <NotificationResultEN> PushTopupRequest(string pPersonEmail, string pRequester, string pAmount)
        {
            NotificationResultEN operationResult = new NotificationResultEN();

            operationResult.Platform    = "ANDROID";
            operationResult.Result      = false;
            operationResult.ServiceName = "Engagement";

            try
            {
                var credentials = await ApplicationTokenProvider.LoginSilentAsync(Constants.TENANT_ID, Constants.CLIENT_ID, Constants.CLIENT_SECRET);

                engagementClient = new EngagementManagementClient(credentials)
                {
                    SubscriptionId = Constants.SUBSCRIPTION_ID
                };

                engagementClient.ResourceGroupName = Constants.RESOURCE_GROUP;
                engagementClient.AppCollection     = Constants.APP_COLLECTION_NAME;
                engagementClient.AppName           = Constants.APP_RESOURCE_NAME_ANDROID;

                Device userDevice = await engagementClient.Devices.GetByUserIdAsync(pPersonEmail);

                Campaign campaign = new Campaign();
                campaign.Type                  = "only_notif";
                campaign.DeliveryTime          = "any";
                campaign.PushMode              = "manual";
                campaign.NotificationType      = "system";
                campaign.NotificationCloseable = true;
                campaign.NotificationTitle     = "¡Nueva solicitud de recarga!";
                campaign.NotificationMessage   = "Hola ${userFirstName}, el número: " + pRequester + " te ha pedido una recarga de " + pAmount + ". Revisa el listado de solicitudes de recarga.";

                List <string> devices = new List <string>();
                devices.Add(userDevice.DeviceId);

                CampaignPushParameters parameters = new CampaignPushParameters(devices, campaign);
                CampaignPushResult     pushResult = await engagementClient.Campaigns.PushAsync(CampaignKinds.Announcements, Constants.TopupRequestCampaign, parameters);

                if (pushResult.InvalidDeviceIds.Count <= 0)
                {
                    //Success
                    operationResult.CodeResult = "Success";
                    operationResult.Result     = true;
                }
            }
            catch (ApiErrorException apiEx)
            {
                if (String.Equals(apiEx.Body.Error.Code, "Conflict"))
                {
                    operationResult.CodeResult = "conflict";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
            }

            return(operationResult);
        }
Exemplo n.º 24
0
        private async Task <ContainerServiceClient> PrepareAKSClientAsync(string tenantId, string clientId, string secret)
        {
            var restCredentials = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, secret);

            var aksManagementClient = new ContainerServiceClient(restCredentials);

            return(aksManagementClient);
        }
Exemplo n.º 25
0
        private static ServiceClientCredentials AuthenticateAzure(string domainName, string clientID, string clientSecret)
        {
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

            var clientCredential = new ClientCredential(clientID, clientSecret);

            return(ApplicationTokenProvider.LoginSilentAsync(domainName, clientCredential).Result);
        }
Exemplo n.º 26
0
        private async Task <DnsManagementClient> PrepareDNSClientAsync(string tenantId, string clientId, string secret)
        {
            var restCredentials = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, secret);

            var dnsManagementClient = new DnsManagementClient(restCredentials);

            return(dnsManagementClient);
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string name = req.Query["name"];

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            name = name ?? data?.name;

            log.LogInformation("Function called by {UserName}", name);

            var workspaceId  = LAWorkSpaceIDAKV;
            var clientId     = clientIDAKV;
            var clientSecret = clientSecretAKV;

            var domain        = "AZURE_AD_DOMAIN_NAME";
            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 client = new OperationalInsightsDataClient(creds)
            {
                WorkspaceId = workspaceId
            };

            // Log Analytics Kusto query - look for data in the past 10 days
            string query = @"
                InformationProtectionLogs_CL
                | where TimeGenerated >= ago(10d)
                | where UserId_s == '*****@*****.**'
                | where ProtectionOwner_s == '*****@*****.**'
                | where Protected_b == 'true'
                | where ObjectId_s != 'document1'
                | where MachineName_s != '' 
                | where ApplicationName_s != 'Outlook'
                | extend FileName = extract('((([a-zA-Z0-9\\s_:]*\\.[a-z]{1,4}$))|([a-zA-Z0-9\\s_:]*$))', 1, ObjectId_s)
                | distinct FileName, Activity_s, LabelName_s, TimeGenerated, Protected_b, MachineName_s
                | sort by TimeGenerated desc nulls last";

            // update the query with caller user's email
            string query1 = query.Replace("*****@*****.**", name);

            var outputTable = client.Query(query1.Trim()).Tables[0];

            // Return results to calling agent as a table
            return(name != null
                ? (ActionResult) new OkObjectResult(outputTable)
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body"));
        }
        public async Task <CPSCloudResourceSummaryModel> GetSummary(string organization, string project, string service, List <string> environments, string feature, CPSAuthCredentialModel authCredential)
        {
            CPSCloudResourceSummaryModel summaryModel = new CPSCloudResourceSummaryModel();

            try
            {
                var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(authCredential.AccessDirectory, authCredential.AccessAppId, authCredential.AccessAppSecret);

                ResourceManagementClient resourceManagementClient = new ResourceManagementClient(serviceCreds);
                resourceManagementClient.SubscriptionId = authCredential.AccessId;

                foreach (var environmentName in environments)
                {
                    string resourceGroupName = $"{organization}{project}{service}{environmentName}{feature}".ToLower();
                    try
                    {
                        var resourceGroupResponse = resourceManagementClient.ResourceGroups.Get(resourceGroupName);
                        if (resourceGroupResponse != null)
                        {
                            var environment = summaryModel.AddEnvironment(environmentName, resourceGroupResponse.Properties.ProvisioningState);
                            var deployments = resourceManagementClient.Deployments.ListByResourceGroup(resourceGroupName, new Microsoft.Rest.Azure.OData.ODataQuery <Microsoft.Azure.Management.ResourceManager.Models.DeploymentExtendedFilter>()
                            {
                                Top = 1, OrderBy = "Name desc"
                            });
                            DeploymentExtended deployment = null;
                            foreach (var item in deployments)
                            {
                                deployment = item;
                                break;
                            }
                            if (deployment != null && deployment.Properties.Outputs != null)
                            {
                                var outPuts = JObject.Parse(JsonConvert.SerializeObject(deployment.Properties.Outputs));
                                foreach (var output in outPuts)
                                {
                                    string key = output.Key.First().ToString().ToUpper() + output.Key.Substring(1);
                                    environment.AddProperty(key, output.Value["value"].ToString());
                                }
                            }
                        }
                        else
                        {
                            summaryModel.AddEnvironment(environmentName, "NO_DEPLOYED_YET");
                        }
                    }
                    catch (System.Exception ex)
                    {
                        summaryModel.AddEnvironment(environmentName, "NO_DEPLOYED_YET");
                    }
                }
            }
            catch (System.Exception)
            {
            }

            return(summaryModel);
        }
Exemplo n.º 29
0
        private async Task CheckAuthentication()
        {
            if (!IsAuthenticated)
            {
                _serviceClientCredentials = await ApplicationTokenProvider.LoginSilentAsync(_domain, _clientCredential);

                _adlsFileSystemClient = new DataLakeStoreFileSystemManagementClient(_serviceClientCredentials);
            }
        }
Exemplo n.º 30
0
        public static async Task <Result <IMonitorManagementClient> > CreateAzureMetricsClientAsync(string azureTenantId, string azureSubscriptionId, string azureAppId, string azureAppKey)
        {
            var credentials = await ApplicationTokenProvider.LoginSilentAsync(azureTenantId, azureAppId, azureAppKey);

            return(new MonitorManagementClient(credentials)
            {
                SubscriptionId = azureSubscriptionId
            });
        }