Esempio n. 1
0
        public void Scenario4_EventHubSendToPublisherWithToken(string sbnamespace, string eventHubEntity, string publisher, string sharedAccessKeyName, string sharedAccessKey)
        {
            string token = SharedAccessSignatureTokenProvider.GetPublisherSharedAccessSignature(
                new Uri(sbnamespace),
                eventHubEntity,
                publisher,
                sharedAccessKeyName,
                sharedAccessKey,
                new TimeSpan(0, 20, 0));

            string connectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessSignature(
                new Uri(sbnamespace),
                eventHubEntity,
                publisher,
                token);

            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connectionString);

            EventHubClient client = factory.CreateEventHubClient(eventHubEntity);

            EventHubSender sender = client.CreateSender(publisher);

            EventData data = new EventData(Encoding.UTF8.GetBytes("Body"));

            data.Properties["time"] = DateTime.UtcNow;

            sender.Send(data);

            sender.Close();
            client.Close();
            factory.Close();
        }
Esempio n. 2
0
 static string GetSasPerPublisher(string endpoint, string keyName, string key, string publisherName)
 {
     return(SharedAccessSignatureTokenProvider.GetPublisherSharedAccessSignature(
                new Uri(endpoint),
                eventHubName,
                publisherName,
                keyName,
                keyValue,
                TimeSpan.FromTicks(DateTime.UtcNow.AddDays(7).Ticks)
                ));
 }
Esempio n. 3
0
        public Task <string> GetTokenAsync(string DeviceId)
        {
            var endpoint = ServiceBusEnvironment.CreateServiceUri("sb", EventHubNamespace, string.Empty);

            // Generate token for the device.
            string deviceToken = SharedAccessSignatureTokenProvider.GetPublisherSharedAccessSignature
                                 (
                endpoint,
                EventHubName,
                DeviceId,
                EventHubSasKeyName,
                EventHubPrimaryKey,
                TimeSpan.FromDays(EventHubTokenLifetimeDays)
                                 );

            return(Task.FromResult(deviceToken));
        }
Esempio n. 4
0
        private static string GenerateKeyForEventHub(
            string namespaceName,
            string eventHubName,
            string publisherName,
            string sharedAccessPolicyName,
            string sharedAccessPolicyKey,
            TimeSpan timeToLive)
        {
            var uri = new Uri($"https://{namespaceName}.servicebus.windows.net");

            return(SharedAccessSignatureTokenProvider.GetPublisherSharedAccessSignature(
                       uri,
                       eventHubName,
                       publisherName,
                       sharedAccessPolicyName,
                       sharedAccessPolicyKey,
                       timeToLive));
        }
Esempio n. 5
0
        private static string GenerateTokenAndCheck(Uri namaSpaceUri, string hubName, string publisher, string policy, string key)
        {
            string token = SharedAccessSignatureTokenProvider.GetPublisherSharedAccessSignature(
                namaSpaceUri,
                hubName,
                publisher,
                policy,
                key,
                new TimeSpan(365, 0, 0));
            var connStr = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessSignature(
                namaSpaceUri,
                hubName,
                publisher,
                token);

            CheckToken(connStr);

            return(token);
        }
        public void ProvisionDevices(bool force)
        {
            //ScenarioSimulatorEventSource.Log.ProvisionDevicesSatarted();

            if (_devices.Any() && !force)
            {
                throw new InvalidOperationException("Devices already provisioned. Use force option to reprovision.");
            }

            _devices.Clear();

            for (int i = 0; i < _simulatorConfiguration.NumberOfDevices; i++)
            {
                // Use the short form of the host or instance name to generate the device id.
                var deviceId = string.Format(CultureInfo.InvariantCulture,
                                             "{0}-{1}",
                                             ConfigurationHelper.InstanceName, i);

                var endpoint     = ServiceBusEnvironment.CreateServiceUri("sb", _simulatorConfiguration.EventHubNamespace, string.Empty);
                var eventHubName = _simulatorConfiguration.EventHubName;

                // Generate token for the device.
                string deviceToken = SharedAccessSignatureTokenProvider.GetPublisherSharedAccessSignature
                                     (
                    endpoint,
                    eventHubName,
                    deviceId,
                    _simulatorConfiguration.EventHubSasKeyName,
                    _simulatorConfiguration.EventHubPrimaryKey,
                    TimeSpan.FromDays(_simulatorConfiguration.EventHubTokenLifetimeDays)
                                     );

                _devices.Add(new Device(deviceId, endpoint, eventHubName, i)
                {
                    Token = deviceToken
                });
            }
        }
Esempio n. 7
0
 public static string GetSas(string publisherId)
 {
     return(SharedAccessSignatureTokenProvider.GetPublisherSharedAccessSignature(new Uri(Namespace), EventHubName, publisherId, "Send", PrimaryKey, new TimeSpan(0, 5, 0)));
 }
Esempio n. 8
0
        static void Main(string[] args)
        {
            string serviceBusConnectionString = ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];

            if (string.IsNullOrWhiteSpace(serviceBusConnectionString))
            {
                Console.WriteLine("Please provide ServiceBus Connection string in App.Config.");
            }

            ServiceBusConnectionStringBuilder connectionString = new ServiceBusConnectionStringBuilder(serviceBusConnectionString);

            string ServiceBusNamespace = connectionString.Endpoints.First().Host;
            string namespaceKeyName    = connectionString.SharedAccessKeyName;
            string namespaceKey        = connectionString.SharedAccessKey;
            string baseAddressHttp     = "https://" + ServiceBusNamespace + "/";
            string eventHubAddress     = baseAddressHttp + EventHubName;

            // Generate device key. The Key is a Base64-encoded key with a length of 256 bits.
            string devicesSendKeyName = "MyDeviceKeyName";
            string primaryDeviceKey   = SharedAccessAuthorizationRule.GenerateRandomKey(); // E.g., "8z9teTzoxORWQNz7yx76MsiajXS9ZgdFs7AxY4DDXuo=".
            string secondaryDeviceKey = SharedAccessAuthorizationRule.GenerateRandomKey(); // E.g., "8z9teTzoxORWQNz7yx76MsiajXS9ZgdFs7AxY4DDXuo=".

            // Create an HttpClientHelper to issue management operations. Use a token that carries namespace-wide Manage rights. You can either use ACS or a SAS key.
            // For ACS: string token = GetAcsToken(ServiceBusNamespace, NamespaceKeyName, NamespaceKey).Result;
            string token = SharedAccessSignatureTokenProvider.GetSharedAccessSignature(namespaceKeyName, namespaceKey, ServiceBusNamespace, TimeSpan.FromMinutes(45));

            HttpClientHelper eventHubHttpClientHelper = new HttpClientHelper(eventHubAddress, token);

            // Create event hub.
            // EventHub creation is demonstrated here just for the ease of running the sample..
            // Creation of EventHub is not a light-weight operation. Consider isolation of Management Operations to Runtime operations in your real-world scenarios.
            Console.WriteLine("Creating event hub ...");
            byte[] eventHubDescription = Encoding.UTF8.GetBytes("<entry xmlns='http://www.w3.org/2005/Atom'><content type='application/xml'>"
                                                                + "<EventHubDescription xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.microsoft.com/netservices/2010/10/servicebus/connect\">"
                                                                + "<AuthorizationRules>"
                                                                + "<AuthorizationRule i:type=\"SharedAccessAuthorizationRule\">"
                                                                + "<ClaimType>SharedAccessKey</ClaimType>"
                                                                + "<ClaimValue>None</ClaimValue>"
                                                                + "<Rights>"
                                                                + "<AccessRights>Send</AccessRights>"
                                                                + "</Rights>"
                                                                + "<KeyName>" + devicesSendKeyName + "</KeyName>"
                                                                + "<PrimaryKey>" + primaryDeviceKey + "</PrimaryKey>"
                                                                + "<SecondaryKey>" + secondaryDeviceKey + "</SecondaryKey>"
                                                                + "</AuthorizationRule>"
                                                                + "</AuthorizationRules>"
                                                                + "<MessageRetentionInDays>3</MessageRetentionInDays>"
                                                                + "<PartitionCount>" + NumberOfPartitions + "</PartitionCount>"
                                                                + "</EventHubDescription></content></entry>");
            int result = eventHubHttpClientHelper.CreateEntity(eventHubDescription).Result;

            if (result < 0)
            {
                Console.WriteLine("\nPress ENTER to exit...\n");
                Console.ReadLine();
            }

            if (result > 0)
            {
                // Event hub exists. Update keys.
                Console.WriteLine("Updating event hub ...");
                eventHubDescription = Encoding.UTF8.GetBytes("<entry xmlns='http://www.w3.org/2005/Atom'><content type='application/xml'>"
                                                             + "<EventHubDescription xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.microsoft.com/netservices/2010/10/servicebus/connect\">"
                                                             + "<AuthorizationRules>"
                                                             + "<AuthorizationRule i:type=\"SharedAccessAuthorizationRule\">"
                                                             + "<ClaimType>SharedAccessKey</ClaimType>"
                                                             + "<ClaimValue>None</ClaimValue>"
                                                             + "<Rights>"
                                                             + "<AccessRights>Send</AccessRights>"
                                                             + "</Rights>"
                                                             + "<KeyName>" + devicesSendKeyName + "</KeyName>"
                                                             + "<PrimaryKey>" + primaryDeviceKey + "</PrimaryKey>"
                                                             + "<SecondaryKey>" + secondaryDeviceKey + "</SecondaryKey>"
                                                             + "</AuthorizationRule>"
                                                             + "</AuthorizationRules>"
                                                             + "</EventHubDescription></content></entry>");
                eventHubHttpClientHelper.UpdateEntity(eventHubDescription).Wait();
            }

            // Query event hub.
            Console.WriteLine("Querying event hub ...");
            byte[] queryEventHubResponse = eventHubHttpClientHelper.GetEntity().Result;
            Console.WriteLine("Event Hub:\n" + Encoding.UTF8.GetString(queryEventHubResponse) + "\n");

            // Create one token per device. The token is specific to the device's publisher.
            // Both tokens either use the primary or the secondary device key.
            string token1 = SharedAccessSignatureTokenProvider.GetPublisherSharedAccessSignature(
                connectionString.Endpoints.First(), EventHubName, "dev-01", devicesSendKeyName, primaryDeviceKey, TimeSpan.FromMinutes(2));

            string token2 = SharedAccessSignatureTokenProvider.GetPublisherSharedAccessSignature(
                connectionString.Endpoints.First(), EventHubName, "dev-02", devicesSendKeyName, primaryDeviceKey, TimeSpan.FromMinutes(2));

            Console.WriteLine("SAS Token 1: " + token1 + "\n");
            Console.WriteLine("SAS Token 2: " + token2 + "\n");

            // Send the first message to the event hub publisher for device dev-01. Payload is JSON-encoded.
            // Message does not contain custom properties. Use token1, which is valid to send to publishers/dev-01.
            Console.WriteLine("Device dev-01 is sending telemetry message 1 ...");
            HttpClientHelper deviceHttpClientHelper1 = new HttpClientHelper(eventHubAddress + "/publishers/dev-01", token1);
            string           messageBody1            = "{\"Temperature\":\"37.0\",\"Humidity\":\"0.4\"}";

            deviceHttpClientHelper1.SendMessage(messageBody1).Wait();

            // Send the second message to the event hub publisher for device dev-02. Payload is JSON-encoded.
            // Message contain a custom property. Use token2, which is valid to send to publishers/dev-02.
            Console.WriteLine("Device dev-02 is sending telemetry message 2 ...");
            HttpClientHelper deviceHttpClientHelper2 = new HttpClientHelper(eventHubAddress + "/publishers/dev-02", token2);
            string           messageBody2            = "{\"Temperature\":\"38.0\",\"Humidity\":\"0.5\"}";

            NameValueCollection customProperties = new NameValueCollection();

            customProperties.Add("WindAlert", "Strong Winds");     // Header name should not contain whitespace.
            customProperties.Add("GeneralAlert", "Thunderstorms"); // Header name should not contain whitespace.
            deviceHttpClientHelper2.SendMessage(messageBody2, customProperties).Wait();

            // Attempt to send the third message to the event hub publisher for device-01.
            // This request fails because we are using token2, which is only valid to send to publishers/dev-02.
            Console.WriteLine("Device dev-02 trying to impersonate dev-01 - using its token. This fails ...");
            HttpClientHelper deviceHttpClientHelper1WithWrongToken = new HttpClientHelper(eventHubAddress + "/publishers/dev-01", token2);
            string           messageBody3 = "{\"Temperature\":\"39.0\",\"Humidity\":\"0.6\"}";

            deviceHttpClientHelper1WithWrongToken.SendMessage(messageBody3).Wait();

            // Revoke - device-02
            // http://blogs.msdn.com/b/servicebus/archive/2015/02/02/event-hub-publisher-policy-in-action.aspx
            Console.WriteLine("Revoked Access to device-02.");
            var namespaceManager = NamespaceManager.CreateFromConnectionString(serviceBusConnectionString);

            namespaceManager.RevokePublisher(EventHubName, "dev-02");

            Console.WriteLine("The subsequent send, even with the correct token fails...");
            deviceHttpClientHelper2.SendMessage(messageBody2, customProperties).Wait();

            // ReInstate device-02. Observe here - that we are using the same token - which was previously issued to this device.
            // PublisherId, which is 'dev-02' - is the only key to revoke or restore access to Event Hub.
            Console.WriteLine("Restore device-02 to send messages to EventHub.");
            namespaceManager.RestorePublisher(EventHubName, "dev-02");

            Console.WriteLine("Now the subsequent sends will succeed.");
            deviceHttpClientHelper2.SendMessage(messageBody2, customProperties).Wait();
            Console.WriteLine("dev-02 sent message to Event Hub.");

            // Start a worker that consumes messages from the event hub.
            EventHubClient      eventHubReceiveClient = EventHubClient.CreateFromConnectionString(serviceBusConnectionString, EventHubName);
            var                 consumerGroup         = eventHubReceiveClient.GetDefaultConsumerGroup();
            EventHubDescription eventHub = namespaceManager.GetEventHub(EventHubName);

            // Register event processor with each shard to start consuming messages
            foreach (var partitionId in eventHub.PartitionIds)
            {
                consumerGroup.RegisterProcessor <DeviceEventProcessor>(new Lease()
                {
                    PartitionId = partitionId
                }, new DeviceProcessorCheckpointManager());
            }

            // Wait for the user to exit this application.
            Console.WriteLine("\nPress ENTER to exit...\n");
            Console.ReadLine();
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            if (1 > args.Length)
            {
                Usage();
                return;
            }

            //
            // Perform the operation indicated by the first command line
            // argument
            //

            if (0 == String.Compare(args[0], OPERATION_REGISTER, true))
            {
                //
                // Create an attested key
                //

                CngProvider cng = new CngProvider(SNKSP);
                CngKeyCreationParameters createParams = new CngKeyCreationParameters();
                createParams.Provider           = cng;
                createParams.KeyCreationOptions = CngKeyCreationOptions.None;

                CngKey snKey = CngKey.Create(
                    CngAlgorithm2.Rsa, ATTESTED_KEY_NAME, createParams);

                //
                // Create a signed request message
                //

                StringBuilder pubKeyHashString    = null;
                byte[]        registrationRequest = CryptoHelper.CreateMessageWithPrependedSignatureAndPublicKey(
                    snKey, ref pubKeyHashString);

                //
                // Save the message
                //

                File.WriteAllBytes(REQUEST_FILE_NAME, registrationRequest);
                Console.WriteLine(
                    "Success: created registration request for publisher ID {0}",
                    pubKeyHashString);
            }
            else if (0 == String.Compare(args[0], OPERATION_PROVIDETOKEN, true))
            {
                //
                // Receive the publisher token request
                //

                byte[] publisherTokenRequest = File.ReadAllBytes(REQUEST_FILE_NAME);

                //
                // Check the signature
                //

                StringBuilder publisherPubKeyHashString = null;
                if (false == CryptoHelper.VerifyMessageWithPrependedSignatureAndPublicKey(
                        publisherTokenRequest, ref publisherPubKeyHashString))
                {
                    return;
                }

                //
                // Read the location of the StrongNet Attestation Server
                //

                RegistryKey snReg =
                    Registry.LocalMachine.OpenSubKey(SNKSP_REG_KEY, false);
                string snAsUri = (string)snReg.GetValue(SNSERVICEURI_REG_VALUE);

                //
                // Confirm with the StrongNet Attestation Server that this is
                // an attested key
                //

                var client = new RestClient(String.Format(
                                                "{0}/{1}", snAsUri, SNAPI_ROOT));
                var request = new RestRequest("MbkAttestation", Method.GET);
                request.AddQueryParameter(
                    "publicKeyHash", publisherPubKeyHashString.ToString());
                var response = client.Execute(request);
                if (System.Net.HttpStatusCode.OK != response.StatusCode ||
                    ResponseStatus.Completed != response.ResponseStatus)
                {
                    Console.WriteLine("Error: invalid publisher token request public key");
                    return;
                }

                //
                // Using Publisher Policy, acquire a shared access token,
                // simulating registration. This would happen on the server in
                // order to limit exposure of the Azure access key.
                //
                // http://blogs.msdn.com/b/servicebus/archive/2015/02/02/event-hub-publisher-policy-in-action.aspx
                //
                // Timespan can be long if the registration server checks every
                // publisher with the attestation server, the event processor checks a
                // signature on every message, publisher IDs can be revoked, and
                // you trust the storage of your policy key.
                //

                string token = SharedAccessSignatureTokenProvider.GetPublisherSharedAccessSignature(
                    new Uri(SERVICE_BUS_URI),
                    EVENT_HUB_NAME,
                    publisherPubKeyHashString.ToString(),
                    SENDER_POLICY_KEY_NAME,
                    args[1],
                    new TimeSpan(0, 30, 0));

                //
                // Send the token back to the requestor
                //

                File.WriteAllText(TOKEN_FILE_NAME, token);
                Console.WriteLine(
                    "Success: issued SAS policy '{0}' token to publisher ID {1}",
                    SENDER_POLICY_KEY_NAME,
                    publisherPubKeyHashString);
            }
            else if (0 == String.Compare(args[0], OPERATION_SENDDATA, true))
            {
                //
                // Read back a previously acquired Azure Service Bus publisher token
                //

                string token = File.ReadAllText(TOKEN_FILE_NAME);

                //
                // Open the attested key
                //

                CngProvider cng   = new CngProvider(SNKSP);
                CngKey      snKey = CngKey.Open(ATTESTED_KEY_NAME, cng);

                //
                // Create a new signed message to simulate what will get posted
                // by each sender to the event hub.
                //

                StringBuilder pubKeyHashString = null;
                byte[]        signedMessage    = CryptoHelper.CreateMessageWithPrependedSignatureAndPublicKey(
                    snKey, ref pubKeyHashString);

                //
                // Create a connection string for this policy and hub. Using
                // the hash of the public key as the publisher identity
                // allows correlation between security policy compliance and
                // sender data streams (but only if the processor verifies a
                // message signature and that the public key is known to the
                // attestation server).
                //

                string connStr = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessSignature(
                    new Uri(SERVICE_BUS_URI),
                    EVENT_HUB_NAME,
                    pubKeyHashString.ToString(),
                    token);

                //
                // Create a sender for this connection
                //

                EventHubSender sender = EventHubSender.CreateFromConnectionString(connStr);

                //
                // Send the signed message
                //

                sender.Send(new EventData(signedMessage));
                Console.WriteLine("Success: message sent");
            }
            else if (0 == String.Compare(args[0], OPERATION_LISTENDATA, true))
            {
                //
                // Create a receiver for the indicated policy
                //

                string evtConnStr = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessKey(
                    new Uri(SERVICE_BUS_URI), LISTEN_POLICY_KEY_NAME, args[1]);
                string storageConnStr = string.Format(
                    "DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}",
                    args[2],
                    args[3]);

                //
                // Use a variation of multi-threaded listener sample code from
                // Microsoft. This saves us from having to know which partition
                // the test message got queued to.
                //
                // http://azure.microsoft.com/en-us/documentation/articles/service-bus-event-hubs-csharp-ephcs-getstarted/
                //

                var processorHost = new EventProcessorHost(
                    Guid.NewGuid().ToString(),
                    EVENT_HUB_NAME,
                    EventHubConsumerGroup.DefaultGroupName,
                    evtConnStr,
                    storageConnStr);
                processorHost.RegisterEventProcessorAsync <SignatureCheckingEventProcessor>().Wait();

                Console.WriteLine("Receiving. Press enter key to stop worker.");
                Console.ReadLine();
            }
            else if (0 == String.Compare(args[0], OPERATION_REVOKEPUBLISHER, true))
            {
                //
                // Create a namespace manager from a connection string acquired
                // from the Azure management portal
                //

                var nsm = Microsoft.ServiceBus.NamespaceManager.CreateFromConnectionString(
                    args[1]);

                //
                // Revoke this publisher
                //

                nsm.RevokePublisher(EVENT_HUB_NAME, args[2]);

                //
                // List revoked publishers
                //

                var revokedPublishers = nsm.GetRevokedPublishers(EVENT_HUB_NAME);

                //
                // Restore this publisher
                //

                nsm.RestorePublisher(EVENT_HUB_NAME, args[2]);
            }
            else
            {
                Usage();
            }
        }