コード例 #1
0
        static async Task Main(string[] args)
        {
            var clientId = "1950a258-227b-4e31-a9cf-717495945fc2"; // "well-known" value: https://blogs.technet.microsoft.com/keithmayer/2014/12/30/leveraging-the-azure-service-management-rest-api-with-azure-active-directory-and-powershell-list-azure-administrators/
            var config   = LoadConfiguration(args);
            //var authorizationRule = "DefaultFullSharedAccessSignature";

            var creds = await UserTokenProvider.LoginByDeviceCodeAsync(clientId, (deviceCodeResult) =>
            {
                Console.WriteLine(deviceCodeResult.Message);
                return(true);
            });

            // Create resource group
            var resourceClient = new ResourceManagementClient(creds);

            resourceClient.SubscriptionId = config.SubscriptionId;
            await resourceClient.ResourceGroups.CreateOrUpdateAsync(config.ResourceGroupName, new ResourceGroup(config.Location));

            var nhManagemntClient = new NotificationHubsManagementClient(creds);

            nhManagemntClient.SubscriptionId = config.SubscriptionId;

            // Create namespace
            await nhManagemntClient.Namespaces.CreateOrUpdateAsync(config.ResourceGroupName, config.NamespaceName, new NamespaceCreateOrUpdateParameters(config.Location)
            {
                Sku = new Microsoft.Azure.Management.NotificationHubs.Models.Sku("standard")
            });

            // Create hub
            Microsoft.Azure.Management.NotificationHubs.Models.GcmCredential  gcmCreds  = null;
            Microsoft.Azure.Management.NotificationHubs.Models.ApnsCredential apnsCreds = null;
            if (config.GcmCreds != null)
            {
                gcmCreds = new Microsoft.Azure.Management.NotificationHubs.Models.GcmCredential
                {
                    GoogleApiKey = config.GcmCreds
                };
            }
            if (config.ApnsCreds != null)
            {
                var apnsCredsSplit = config.ApnsCreds.Replace("\\n", "\n").Split(";");
                apnsCreds = new Microsoft.Azure.Management.NotificationHubs.Models.ApnsCredential
                {
                    KeyId = apnsCredsSplit[0],
                    // Id
                    AppName = apnsCredsSplit[1],
                    // Prefix
                    AppId    = apnsCredsSplit[2],
                    Token    = apnsCredsSplit[3],
                    Endpoint = "https://api.development.push.apple.com:443/3/device"
                };
            }
            await nhManagemntClient.NotificationHubs.CreateOrUpdateAsync(config.ResourceGroupName, config.NamespaceName, config.HubName, new NotificationHubCreateOrUpdateParameters(config.Location)
            {
                GcmCredential  = gcmCreds,
                ApnsCredential = apnsCreds
            });

            Console.WriteLine($"Create NotificationHub {config.HubName}.");
        }
コード例 #2
0
        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);
        }
コード例 #3
0
        public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var adSettings = new ActiveDirectoryServiceSettings
            {
                AuthenticationEndpoint = new Uri(Environment.AuthenticationEndpoint),
                TokenAudience          = new Uri(Environment.ManagementEndpoint),
                ValidateAuthority      = true
            };

            var 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);
                    }
                    else
                    {
                        _credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync(
                            TenantId, _servicePrincipalLoginInformation.ClientId, _servicePrincipalLoginInformation.Certificate, _servicePrincipalLoginInformation.CertificatePassword, TokenCache.DefaultShared);
                    }
                }
                //else if (_userLoginInformation != null) //Not supported in .Net Core. UserTokenProvider.LoginSilentAsync does not exist
                //{
                //    _credentialsCache[adSettings.TokenAudience] = await UserTokenProvider.LoginSilentAsync(
                //        _userLoginInformation.ClientId, TenantId, _userLoginInformation.UserName,
                //        _userLoginInformation.Password, adSettings, TokenCache.DefaultShared);
                //}
                else if (_deviceCredentialInformation != null)
                {
                    _credentialsCache[adSettings.TokenAudience] = await UserTokenProvider.LoginByDeviceCodeAsync(
                        _deviceCredentialInformation.ClientId, TenantId, adSettings, TokenCache.DefaultShared, _deviceCredentialInformation.DeviceCodeFlowHandler);
                }
            }
            await _credentialsCache[adSettings.TokenAudience].ProcessHttpRequestAsync(request, cancellationToken);
        }
コード例 #4
0
        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);
            }

            string host = request.RequestUri.Host;

            if (host.EndsWith(Environment.KeyVaultSuffix, StringComparison.OrdinalIgnoreCase))
            {
                var resource = new Uri(Regex.Replace(Environment.KeyVaultSuffix, "^.", "https://"));
                if (credentialsCache.ContainsKey(new Uri(Regex.Replace(Environment.KeyVaultSuffix, "^.", "https://"))))
                {
                    adSettings.TokenAudience = resource;
                }
                else
                {
                    using (var r = new HttpRequestMessage(request.Method, url))
                    {
                        var response = await new HttpClient().SendAsync(r).ConfigureAwait(false);

                        if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized && response.Headers.WwwAuthenticate != null)
                        {
                            var header = response.Headers.WwwAuthenticate.ElementAt(0).ToString();
                            var regex  = new Regex("authorization=\"([^\"]+)\"");
                            var match  = regex.Match(header);
                            adSettings.AuthenticationEndpoint = new Uri(match.Groups[1].Value);
                            regex = new Regex("resource=\"([^\"]+)\"");
                            match = regex.Match(header);
                            adSettings.TokenAudience = new Uri(match.Groups[1].Value);
                        }
                    }
                }
            }

            if (!credentialsCache.ContainsKey(adSettings.TokenAudience))
            {
                if (servicePrincipalLoginInformation != null)
                {
                    if (servicePrincipalLoginInformation.ClientId == null)
                    {
                        throw new RestException($"Cannot communicate with server. ServicePrincipalLoginInformation should contain a valid ClientId information.");
                    }
                    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);
                    }
#else
                    else if (servicePrincipalLoginInformation.X509Certificate != null)
                    {
                        credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync(
                            TenantId, new Microsoft.Rest.Azure.Authentication.ClientAssertionCertificate(servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.X509Certificate), adSettings, TokenCache.DefaultShared);
                    }
#endif
                    else if (servicePrincipalLoginInformation.Certificate != null)
                    {
                        credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync(
                            TenantId, servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.Certificate, servicePrincipalLoginInformation.CertificatePassword, adSettings, TokenCache.DefaultShared);
                    }
                    else
                    {
                        throw new RestException($"Cannot communicate with server. ServicePrincipalLoginInformation should contain either a valid ClientSecret or Certificate information.");
                    }
                }
#if NET45
                else if (userLoginInformation != null)
                {
                    credentialsCache[adSettings.TokenAudience] = await UserTokenProvider.LoginSilentAsync(
                        userLoginInformation.ClientId, TenantId, userLoginInformation.UserName,
                        userLoginInformation.Password, adSettings, TokenCache.DefaultShared);
                }
#else
                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));
                }
                // no token available for communication
                else
                {
                    throw new RestException($"Cannot communicate with server. No authentication token available for '{adSettings.TokenAudience}'.");
                }
            }
            await credentialsCache[adSettings.TokenAudience].ProcessHttpRequestAsync(request, cancellationToken);
        }
コード例 #5
0
 public static ServiceClientCredentials GetCredentialFromPrompt(TokenCache tokenCache)
 {
     SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
     return(UserTokenProvider.LoginByDeviceCodeAsync(GetCredentialFromPromptClientId, DomainOrTenantId, ServiceSettings, DeviceCodeHandler).GetAwaiter().GetResult());
 }