Exemplo n.º 1
0
        async Task ClientCredentialsCertScenario()
        {
            X509Certificate2 certificate = GetCertificate();

            AzureActiveDirectoryTokenProvider.AuthenticationCallback authCallback = async(audience, authority, state) =>
            {
                IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(ClientId)
                                                     .WithAuthority(authority)
                                                     .WithCertificate(certificate)
                                                     .Build();

                var serviceBusAudience = new Uri("https://servicebus.azure.net");

                var authResult = await app.AcquireTokenForClient(new string[] { $"{serviceBusAudience}/.default" }).ExecuteAsync();

                return(authResult.AccessToken);
            };

            QueueClient qc = QueueClient.CreateWithAzureActiveDirectory(
                new Uri($"sb://{ServiceBusNamespace}/"),
                QueueName,
                authCallback,
                $"https://login.windows.net/{TenantId}");

            await SendReceiveAsync(qc);
        }
Exemplo n.º 2
0
        /// <summary>Creates an Azure Active Directory token provider.</summary>
        /// <param name="authCallback">The authentication delegate to provide access token.</param>
        /// <param name="authority">Address of the authority to issue token.</param>
        /// <param name="state">State to be delivered to callback.</param>
        /// <returns>The <see cref="TokenProvider" /> for returning Json web token.</returns>
        public static TokenProvider CreateAzureActiveDirectoryTokenProvider(
            AzureActiveDirectoryTokenProvider.AuthenticationCallback authCallback,
            string authority = AzureActiveDirectoryTokenProvider.CommonAuthority,
            object state     = null)
        {
            Guard.ArgumentNotNull(nameof(authCallback), authCallback);
            Guard.ArgumentNotNullOrWhiteSpace(nameof(authority), authority);

            return(new AzureActiveDirectoryTokenProvider(authCallback, authority, state));
        }
Exemplo n.º 3
0
        /// <param name="authCallback">The user defined authentication delegate to provide access token.</param>
        /// <param name="authority">URL of the Azure Active Directory instance to issue token.</param>
        /// <param name="state">Custom parameters that may be passed into the authentication delegate.</param>
        /// <returns>The <see cref="Microsoft.Azure.ServiceBus.Primitives.TokenProvider" /> for returning Json web token.</returns>
        public static TokenProvider CreateAzureActiveDirectoryTokenProvider(
            AzureActiveDirectoryTokenProvider.AuthenticationCallback authCallback,
            string authority,
            object state = null)
        {
            if (authCallback == null)
            {
                throw new ArgumentNullException(nameof(authCallback));
            }

            return(new AzureActiveDirectoryTokenProvider(authCallback, authority, state));
        }
        public async Task UseITokenProviderWithAad()
        {
            var appAuthority = "";
            var aadAppId     = "";
            var aadAppSecret = "";

            AzureActiveDirectoryTokenProvider.AuthenticationCallback authCallback =
                async(audience, authority, state) =>
            {
                var authContext = new AuthenticationContext(authority);
                var cc          = new ClientCredential(aadAppId, aadAppSecret);
                var authResult  = await authContext.AcquireTokenAsync(audience, cc);

                return(authResult.AccessToken);
            };

            var tokenProvider = TokenProvider.CreateAzureActiveDirectoryTokenProvider(authCallback, appAuthority);

            // Create new client with updated connection string.
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                var csb      = new EventHubsConnectionStringBuilder(connectionString);
                var ehClient = EventHubClient.CreateWithTokenProvider(csb.Endpoint, csb.EntityPath, tokenProvider);

                // Send one event
                TestUtility.Log($"Sending one message.");
                var ehSender  = ehClient.CreatePartitionSender("0");
                var eventData = new EventData(Encoding.UTF8.GetBytes("Hello EventHub!"));
                await ehSender.SendAsync(eventData);

                // Receive event.
                PartitionReceiver ehReceiver = null;
                try
                {
                    TestUtility.Log($"Receiving one message.");
                    ehReceiver = ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, "0", EventPosition.FromStart());
                    var msg = await ehReceiver.ReceiveAsync(1);

                    Assert.True(msg != null, "Failed to receive message.");
                }
                finally
                {
                    await ehReceiver?.CloseAsync();
                }
            }
        }
Exemplo n.º 5
0
        /// <summary>Creates a new instance of the
        /// <see cref="EventHubClient" /> by using Azure Active Directory authentication.</summary>
        /// <param name="endpointAddress">Fully qualified domain name for Event Hubs. Most likely, {yournamespace}.servicebus.windows.net</param>
        /// <param name="path">The path to the Event Hub.</param>
        /// <param name="authCallback">The authentication callback.</param>
        /// <param name="authority">Address of the authority to issue token.</param>
        /// <param name="operationTimeout">Operation timeout for Event Hubs operations.</param>
        /// <param name="transportType">Transport type on connection.</param>
        /// <returns>The newly created Event Hub client object.</returns>
        public static EventHubClient CreateWithAzureActiveDirectory(
            Uri endpointAddress,
            string path,
            AzureActiveDirectoryTokenProvider.AuthenticationCallback authCallback,
            string authority            = AzureActiveDirectoryTokenProvider.CommonAuthority,
            TimeSpan?operationTimeout   = null,
            TransportType transportType = TransportType.Amqp)
        {
            TokenProvider tokenProvider = TokenProvider.CreateAzureActiveDirectoryTokenProvider(authCallback, authority);

            return(CreateWithTokenProvider(
                       endpointAddress,
                       path,
                       tokenProvider,
                       operationTimeout,
                       transportType));
        }
Exemplo n.º 6
0
        /// <summary>
        /// Creates an <see cref="AzureActiveDirectoryTokenProvider"/> using interactive login. If no redirect url is provided <see cref="DefaultAzureCredential"/> is used.
        /// </summary>
        /// <param name="redirectUri">The uri to redirect to after interactive login</param>
        /// <returns><see cref="AzureActiveDirectoryTokenProvider"/></returns>
        public AzureActiveDirectoryTokenProvider WithInteractive(string redirectUri, Action <DefaultAzureCredentialOptions> optBuilder = null)
        {
            AzureActiveDirectoryTokenProvider.AuthenticationCallback authCallback = async(audience, authority, state) =>
            {
                if (string.IsNullOrWhiteSpace(redirectUri))
                {
                    return((await GetTokenFromDefaultAzureCredential(optBuilder)).Token);
                }

                IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(_clientId)
                                                     .WithRedirectUri(redirectUri)
                                                     .Build();

                var authResult = await app.AcquireTokenForClient(_requestContext.Scopes).ExecuteAsync();

                return(authResult.AccessToken);
            };

            return(new AzureActiveDirectoryTokenProvider(authCallback, "", null));
        }
Exemplo n.º 7
0
        public async Task CreateWithAzureActiveDirectory()
        {
            await using var scope = await EventHubScope.CreateAsync(1);

            #region Snippet:EventHubs_Migrate_T1_CreateWithAzureActiveDirectory
#if SNIPPET
            var fullyQualifiedNamespace = "<< NAMESPACE (likely similar to {your-namespace}.servicebus.windows.net) >>";
            var eventHubName            = "<< NAME OF THE EVENT HUB >>";

            var authority    = "<< NAME OF THE AUTHORITY TO ASSOCIATE WITH THE TOKEN >>";
            var aadAppId     = "<< THE AZURE ACTIVE DIRECTORY APPLICATION ID TO REQUEST A TOKEN FOR >>";
            var aadAppSecret = "<< THE AZURE ACTIVE DIRECTORY SECRET TO USE FOR THE TOKEN >>";
#else
            var fullyQualifiedNamespace = new EventHubsConnectionStringBuilder(TestUtility.EventHubsConnectionString).Endpoint.ToString();
            var eventHubName            = scope.EventHubName;
            var authority    = "";  // Needed for manual run
            var aadAppId     = "";  // Needed for manual run
            var aadAppSecret = "";  // Needed for manual run
#endif

            AzureActiveDirectoryTokenProvider.AuthenticationCallback authCallback =
                async(audience, authority, state) =>
            {
                var authContext      = new AuthenticationContext(authority);
                var clientCredential = new ClientCredential(aadAppId, aadAppSecret);

                AuthenticationResult authResult = await authContext.AcquireTokenAsync(audience, clientCredential);

                return(authResult.AccessToken);
            };

            EventHubClient client = EventHubClient.CreateWithAzureActiveDirectory(
                new Uri(fullyQualifiedNamespace),
                eventHubName,
                authCallback,
                authority);

            #endregion

            client.Close();
        }
Exemplo n.º 8
0
        /// <summary>
        /// Creates an <see cref="AzureActiveDirectoryTokenProvider"/> using a certificate. If no thumbprint is provided <see cref="DefaultAzureCredential"/> is used.
        /// </summary>
        /// <param name="thumbPrint">The thumbprint of the certificate to use for authentication</param>
        /// <param name="authority">A URL that indicates a directory that MSAL can request tokens from. For example, https://login.microsoftonline.com/{AzureADTenantID}/
        /// <param name="validCertsOnly">Indicates if only valid certificates are can be found and used from the X509 cert store. If using self-signed certs, this value should be false.</param>
        /// <returns><see cref="AzureActiveDirectoryTokenProvider"/></returns>
        public AzureActiveDirectoryTokenProvider WithCert(string thumbPrint, string authority, bool validCertsOnly, Action <DefaultAzureCredentialOptions> optBuilder = null)
        {
            AzureActiveDirectoryTokenProvider.AuthenticationCallback authCallback = async(audience, authority, state) =>
            {
                if (string.IsNullOrWhiteSpace(thumbPrint))
                {
                    return((await GetTokenFromDefaultAzureCredential(optBuilder)).Token);
                }

                var cert = GetCertificate(thumbPrint, validCertsOnly);

                IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(_clientId)
                                                     .WithAuthority(authority)
                                                     .WithCertificate(cert)
                                                     .Build();

                var authResult = await app.AcquireTokenForClient(_requestContext.Scopes).ExecuteAsync();

                return(authResult.AccessToken);
            };

            return(new AzureActiveDirectoryTokenProvider(authCallback, authority ?? "", null));
        }
Exemplo n.º 9
0
        async Task UserInteractiveLoginScenario()
        {
            AzureActiveDirectoryTokenProvider.AuthenticationCallback authCallback = async(audience, authority, state) =>
            {
                var app = PublicClientApplicationBuilder.Create(ClientId)
                          .WithRedirectUri(ConfigurationManager.AppSettings["redirectURI"])
                          .Build();

                var serviceBusAudience = new Uri("https://servicebus.azure.net");

                var authResult = await app.AcquireTokenInteractive(new string[] { $"{serviceBusAudience}/.default" }).ExecuteAsync();

                return(authResult.AccessToken);
            };

            QueueClient qc = QueueClient.CreateWithAzureActiveDirectory(
                new Uri($"sb://{ServiceBusNamespace}/"),
                QueueName,
                authCallback,
                $"https://login.windows.net/{TenantId}");

            await SendReceiveAsync(qc);
        }