示例#1
0
        private static async Task ProvisionDeviceAsync(CancellationToken token)
        {
            string baseUrl = ConfigurationHelper.GetConfigValue <string>("WebApiEndpoint");

            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri(baseUrl);

            string urlPath = String.Format("api/devices/{0}/provision", DEVICE_ID);

            var result = await client.PostAsync(urlPath, null, token);

            Console.WriteLine("{0} ({1})", (int)result.StatusCode, result.ReasonPhrase);
            if (result.IsSuccessStatusCode)
            {
                var endpoint = await result.Content.ReadAsAsync <DeviceEndpoint>(token);

                Console.WriteLine("Endpoint: {0}", endpoint.Uri);
                Console.WriteLine("AccessToken: {0}", endpoint.AccessToken);

                ConnectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessSignature(
                    new Uri(endpoint.Uri),
                    endpoint.EventHubName,
                    DEVICE_ID,
                    endpoint.AccessToken
                    );
            }
            else if (result.StatusCode == HttpStatusCode.NotFound)
            {
                Console.WriteLine("You must register the device first.");
            }
        }
示例#2
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();
        }
示例#3
0
        static void SendMessagesWithSas(string endpoint, string eventHubName, string publisherName, string sas)
        {
            var sasConnectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessSignature(new Uri(endpoint), eventHubName, publisherName, sas);
            var sender = EventHubSender.CreateFromConnectionString(sasConnectionString);

            var message = Guid.NewGuid().ToString();

            Console.WriteLine("{0} > Sending message with SAS connection string : {1} from publisher {2}", DateTime.Now, message, publisherName);
            var eventData = new EventData(Encoding.UTF8.GetBytes(message));

            // Below partition key setting is not neccessary as it will be auto assigned with publishername in such scenario
            //eventData.PartitionKey = publisherName;

            try
            {
                sender.Send(eventData);
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("{0} > Sent message {1} succesfully!", DateTime.Now, message);
                Console.ResetColor();
            }
            catch (Exception exception)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("{0} > Exception: {1}", DateTime.Now, exception.Message);
                Console.ResetColor();
            }
        }
示例#4
0
        public void Send(string a)
        {
            var sas = GetSas();
            //Console.WriteLine("Creating EHSender");
            var xon = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessSignature(new Uri(_sbNamespace), _hubName, _publisherName, sas);
            var c   = EventHubSender.CreateFromConnectionString(xon);

            c.SendAsync(new EventData(System.Text.Encoding.UTF8.GetBytes($"{_publisherName} says {a}")));
            //Console.WriteLine("Sent.");
        }
示例#5
0
        private static EventHubSender CreateSender()
        {
            var publisher = "handsonazurepublisher";
            var token     = SharedAccessSignatureTokenProvider.GetSharedAccessSignature(KeyName, SASKey,
                                                                                        $"sb://{Namespace}.servicebus.windows.net/{HubName}/publishers/{publisher}", TimeSpan.FromHours(24));
            var connectionString =
                ServiceBusConnectionStringBuilder.CreateUsingSharedAccessSignature(
                    new Uri($"sb://{Namespace}.servicebus.windows.net"), HubName, publisher, token);
            var eventHubSender = EventHubSender.CreateFromConnectionString(connectionString);

            return(eventHubSender);
        }
示例#6
0
        public EventHubReporter(ServiceDescriptor service, EventHubConnectionInfo eventHubConnection)
        {
            Require.NotNull(service, nameof(service));
            Require.NotNull(eventHubConnection, nameof(eventHubConnection));

            var connectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessSignature(
                endpoint: eventHubConnection.Namespace,
                entityPath: eventHubConnection.Hub,
                publisher: MetricsPublihser.GetPublisherId(service),
                sharedAccessSignature: eventHubConnection.SharedAccessSignature);

            m_service            = service;
            m_eventHubConnection = eventHubConnection;
            m_sender             = EventHubSender.CreateFromConnectionString(connectionString);
        }
示例#7
0
        public EventSender(
            Device device,
            SimulatorConfiguration config,
            Func <object, byte[]> serializer)
        {
            this._serializer = serializer;

            var connectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessSignature(
                device.Endpoint,
                device.EventHubName,
                device.Id,
                device.Token
                );

            _eventHubSender = EventHubSender.CreateFromConnectionString(connectionString);
        }
示例#8
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);
        }
示例#9
0
文件: Program.cs 项目: hdracer/HIISDA
        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();
            }
        }