Пример #1
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="baseAddress">Base address to service bus</param>
        /// <param name="settings">AMQP transport settings</param>
        public AmqpMessagingFactory(Uri baseAddress, AmqpTransportSettings settings)
        {
            this.Address           = baseAddress;
            this.TransportSettings = settings;

            SharedAccessSignatureTokenProvider sasTokenProvider = (SharedAccessSignatureTokenProvider)this.TransportSettings.TokenProvider;

            this.amqpAddress = new Address(this.Address.Host, this.TransportSettings.Port, sasTokenProvider.KeyName, sasTokenProvider.SharedAccessKey);
        }
Пример #2
0
        public static string CreateForHttpSender(string senderKeyName, string senderKey, string serviceNamespace, string hubName, string publisherName, TimeSpan tokenTimeToLive)
        {
            var serviceUri = ServiceBusEnvironment.CreateServiceUri(
                "https", serviceNamespace, String.Format("{0}/publishers/{1}/messages", hubName, publisherName))
                             .ToString()
                             .Trim('/');

            var sas = SharedAccessSignatureTokenProvider.GetSharedAccessSignature(senderKeyName, senderKey, serviceUri, tokenTimeToLive);

            return(sas);
        }
Пример #3
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)
                ));
 }
Пример #4
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);
        }
Пример #5
0
    protected void btnGenerate_Click(object sender, EventArgs e)
    {
        var nameSpace  = txtNamespace.Text;
        var eventHub   = txtEventHub.Text;
        var policyName = txtPolicyName.Text;
        var policyKey  = txtPolicyKey.Text;
        var ttl        = TimeSpan.FromMinutes(Convert.ToDouble(txtTTL.Text));

        var resource = ServiceBusEnvironment.CreateServiceUri("https", nameSpace, eventHub).ToString().Trim('/');

        lblResult.Text = SharedAccessSignatureTokenProvider.GetSharedAccessSignature(policyName, policyKey, resource, ttl);
    }
Пример #6
0
        //生成sastoken
        static string gettoken()
        {
            ServiceBusConnectionStringBuilder connectionString = new ServiceBusConnectionStringBuilder("Endpoint=sb://wanderhub-ns.servicebus.chinacloudapi.cn/;SharedAccessKeyName=ReceiveRule;SharedAccessKey=5WVrbt3P707PBF41owIbM0300u+jjGlT7gV35Baou0c=");

            string ServiceBusNamespace = connectionString.Endpoints.First().Host;
            string namespaceKeyName    = connectionString.SharedAccessKeyName;
            string namespaceKey        = connectionString.SharedAccessKey;

            // Create a token valid for 45mins
            string token = SharedAccessSignatureTokenProvider.GetSharedAccessSignature(namespaceKeyName, namespaceKey, ServiceBusNamespace, TimeSpan.FromDays(365));

            return(token);
        }
Пример #7
0
        private static string CreateSharedAccessSignature()
        {
            string eventHubResourcePath = string.Format("https://{0}.servicebus.windows.net/{1}", EventHubServiceNamespace, EventHubName);

            DateTime now             = DateTime.Now;
            TimeSpan expireationDate = now.AddYears(1) - now;

            var sas = SharedAccessSignatureTokenProvider.GetSharedAccessSignature(EventHubNamespaceManageKeyName,
                                                                                  EventHubNamespaceManageKey,
                                                                                  eventHubResourcePath,
                                                                                  expireationDate);

            return(sas);
        }
Пример #8
0
        private static string GenerateKeyForServiceBus(
            string namespaceName,
            string queueName,
            string sharedAccessPolicyName,
            string sharedAccessPolicyKey,
            TimeSpan timeToLive)
        {
            var uri = $"https://{namespaceName}.servicebus.windows.net/{queueName}/messages";

            return(SharedAccessSignatureTokenProvider.GetSharedAccessSignature(
                       sharedAccessPolicyName,
                       sharedAccessPolicyKey,
                       uri,
                       timeToLive));
        }
Пример #9
0
        /// Initializes a new instance of <see cref="NamespaceManager"/> with settings
        /// <param name="connectionString">Namespace connection string</param>
        /// <param name="settings"> Namespace manager settings. </param>
        public NamespaceManager(string connectionString, NotificationHubSettings settings)
        {
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new ArgumentNullException(nameof(connectionString));
            }

            _tokenProvider = SharedAccessSignatureTokenProvider.CreateSharedAccessSignatureTokenProvider(connectionString);
            var configurationManager = new KeyValueConfigurationManager(connectionString);

            _baseUri = GetBaseUri(configurationManager);
            settings = settings ?? new NotificationHubSettings();

            if (settings.HttpClient != null)
            {
                _httpClient = settings.HttpClient;
            }
            else if (settings.MessageHandler != null)
            {
                var httpClientHandler = settings.MessageHandler;
                _httpClient = new HttpClient(httpClientHandler);
            }
            else if (settings.Proxy != null)
            {
                var httpClientHandler = new HttpClientHandler();
                httpClientHandler.UseProxy = true;
                httpClientHandler.Proxy    = settings.Proxy;
                _httpClient = new HttpClient(httpClientHandler);
            }
            else
            {
                _httpClient = new HttpClient();
            }

            if (settings.OperationTimeout == null)
            {
                OperationTimeout = TimeSpan.FromSeconds(60);
            }
            else
            {
                OperationTimeout = settings.OperationTimeout.Value;
            }

            _retryPolicy = settings.RetryOptions.ToRetryPolicy();

            _httpClient.Timeout = OperationTimeout;
            SetUserAgent();
        }
Пример #10
0
        public void ListenForMessages()
        {
            if (_isRunning != null && !_isRunning.IsCompleted)
            {
                return;
            }

            var address = new Uri(CommonConfiguration.Instance.BackboneConfiguration.GetServiceSubscriptionsAddress(Queue, CommonConfiguration.Instance.PlayerId));

            try
            {
                WebRequest request = WebRequest.Create(address);

                if (_sasProvider == null)
                {
                    _sasProvider = new SharedAccessSignatureTokenProvider(CommonConfiguration.Instance.BackboneConfiguration.IssuerName,
                                                                          CommonConfiguration.Instance.BackboneConfiguration.IssuerSecret,
                                                                          new TimeSpan(1, 0, 0));
                }

                var token = _sasProvider.GetToken(CommonConfiguration.Instance.BackboneConfiguration.GetRealm(), "POST", new TimeSpan(1, 0, 0));
                request.Headers[HttpRequestHeader.Authorization] = token.TokenValue;
                request.Method = "DELETE";
                RequestState rs = new RequestState();
                rs.Request = request;

                _isRunning = request.BeginGetResponse(new AsyncCallback(RespCallback), rs);
            }
            catch (WebException ex)
            {
                // if the server has not created a topic yet for the client then a 404 error will be returned so do not report
                if (!ex.Message.Contains("The remote server returned an error: (404) Not Found"))
                {
                    if (OnListenError != null)
                    {
                        OnListenError.Invoke(this, new System.IO.ErrorEventArgs(ex));
                    }
                }
            }
            catch (Exception ex)
            {
                if (OnListenError != null)
                {
                    OnListenError.Invoke(this, new System.IO.ErrorEventArgs(ex));
                }
            }
        }
Пример #11
0
        static void Main(string[] args)
        {
            Console.WriteLine("What is your service bus namespace?");
            string sbNamespace = Console.ReadLine();

            Console.WriteLine();
            Console.WriteLine("What is the Notification Hub name?");
            string sbPath = Console.ReadLine();

            Console.WriteLine();
            Console.WriteLine("What existing shared access policy would you like to use to generate your SAS? (press enter for 'DefaultFullSharedAccessSignature')");
            string sbPolicy = Console.ReadLine();
            if (sbPolicy.Length == 0) sbPolicy = "DefaultFullSharedAccessSignature";

            Console.WriteLine();
            Console.WriteLine("What is that policy's shared access key?");
            string sbKey = Console.ReadLine();

            Console.WriteLine();
            Console.WriteLine("When should this expire (MM/DD/YY HH, GMT)? (press enter for 10/31/2020 12:00)");
            string sbExpiry = Console.ReadLine();
            if (sbExpiry.Length == 0) sbExpiry = "10/31/2020 12";

            // convert the expiry date string into a timespan... 
            DateTime tmpDT;
            DateTime.TryParseExact(sbExpiry, "MM/dd/YY HH", null, DateTimeStyles.None, out tmpDT);
            TimeSpan expiry = DateTime.UtcNow.Subtract(tmpDT);

            Console.WriteLine();
            try
            {
                var serviceUri = ServiceBusEnvironment.CreateServiceUri("https", sbNamespace, sbPath).ToString().Trim('/');
                string generatedSaS = SharedAccessSignatureTokenProvider.GetSharedAccessSignature(sbPolicy, sbKey, serviceUri, expiry);
               
                Console.WriteLine("Your SAS is:\n{0}", generatedSaS);
                Console.WriteLine();
                Console.WriteLine("Copy the above generated key");
            }
            catch
            {
                Console.WriteLine("An error occured, please check the values you entered and try again");
            }
           
            
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            Uri    address        = ServiceBusEnvironment.CreateServiceUri("https", ConfigurationManager.AppSettings["RelayServiceNamespace"], "Hybrid");
            string tokenForClient = SharedAccessSignatureTokenProvider.GetSharedAccessSignature(
                ConfigurationManager.AppSettings["ClientKeyName"],
                ConfigurationManager.AppSettings["ClientKey"],
                address.ToString(),
                new TimeSpan(0, 1, 1, 1));

            WebServiceHost host = new WebServiceHost(typeof(HybridService), address);

            host.Open();

            Console.ReadLine();

            host.Close();
        }
Пример #13
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));
        }
        public static string CreateSasTokenForAmqpSender(string senderKeyName,
                                                         string senderKey,
                                                         string serviceNamespace,
                                                         string hubName,
                                                         string publisherName,
                                                         TimeSpan tokenTimeToLive)
        {
            // This is the format of the publisher endpoint. Each device uses a different publisher endpoint.
            // sb://<NAMESPACE>.servicebus.windows.net/<EVENT_HUB_NAME>/publishers/<PUBLISHER_NAME>.
            var serviceUri = ServiceBusEnvironment.CreateServiceUri("sb",
                                                                    serviceNamespace,
                                                                    $"{hubName}/publishers/{publisherName}")
                             .ToString()
                             .Trim('/');

            // SharedAccessSignature sr=<URL-encoded-resourceURI>&sig=<URL-encoded-signature-string>&se=<expiry-time-in-ISO-8061-format. >&skn=<senderKeyName>
            return(SharedAccessSignatureTokenProvider.GetSharedAccessSignature(senderKeyName, senderKey, serviceUri, tokenTimeToLive));
        }
Пример #15
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));
        }
Пример #16
0
        public ActionResult Create(FormCollection collection)
        {
            var serviceNamespace = collection["Namespace"];
            var servicePath      = collection["Path"];
            var keyName          = collection["KeyName"];
            var key        = collection["Key"];
            var expiration = collection["Expiration"];

            var parsedExpiration = DateTime.Parse(expiration);
            var ttl = parsedExpiration.Subtract(DateTime.UtcNow);

            var resource = ServiceBusEnvironment.CreateServiceUri("https", serviceNamespace, servicePath).ToString().Trim('/');
            var sasToken = SharedAccessSignatureTokenProvider.GetSharedAccessSignature(keyName, key, resource, ttl);

            var encodedToken = HttpServerUtility.UrlTokenEncode(Encoding.ASCII.GetBytes(sasToken));

            return(RedirectToAction("DisplaySas", new { id = encodedToken }));
        }
Пример #17
0
        public static string CreateForHttpSender(string senderKeyName, string senderKey, string serviceNamespace, string hubName, string publisherName, TimeSpan tokenTimeToLive)
        {
            var servicePath = string.Empty;

            if (publisherName == null || publisherName.Length <= 0)
            {
                servicePath = String.Format("{0}/messages", hubName);
            }
            else
            {
                servicePath = String.Format("{0}/publishers/{1}/messages", hubName, publisherName);
            }

            var serviceUri = ServiceBusEnvironment.CreateServiceUri("https", serviceNamespace, servicePath)
                             .ToString()
                             .Trim('/');

            return(SharedAccessSignatureTokenProvider.GetSharedAccessSignature(senderKeyName, senderKey, serviceUri, tokenTimeToLive));
        }
Пример #18
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);
        }
Пример #19
0
 internal override bool OpenConnection()
 {
     if (this.Connection == null)
     {
         if (this.TransportSettings.TokenProvider.GetType() == typeof(SharedAccessSignatureTokenProvider))
         {
             SharedAccessSignatureTokenProvider tokenProvider = (SharedAccessSignatureTokenProvider)this.TransportSettings.TokenProvider;
             if ((tokenProvider.ShareAccessSignature != null) && (tokenProvider.ShareAccessSignature != string.Empty))
             {
                 this.Connection = new Connection(this.amqpAddress, global::Amqp.Sasl.SaslProfile.External, null, null);
             }
             else
             {
                 this.Connection = new Connection(this.amqpAddress);
             }
         }
     }
     return(true);
 }
Пример #20
0
        static void Main(string[] args)
        {
            var sbNameSpace = "hemanttestsb";
            var sbPath      = "testtopic";
            var sbPolicy    = "Send";
            var sbKey       = "mVvckbUWiTm7xOIpCs7mFGRtYfMUlcNVHrTfvQaWU8Q=";
            var expiry      = new TimeSpan(100, 1, 1, 1);

            try
            {
                var serviceUri = ServiceBusEnvironment.CreateServiceUri("https", sbNameSpace, sbPath).ToString().Trim('/');

                var sas = SharedAccessSignatureTokenProvider.GetSharedAccessSignature(sbPolicy, sbKey, serviceUri, expiry);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Пример #21
0
        private async Task <string> GetSharedAccessSignature(string ruleName)
        {
            var queueName = configuration.Find("QueueName");

            var manager     = NamespaceManager.CreateFromConnectionString(configuration.Find("ServiceBusConnectionString"));
            var description = await manager.GetQueueAsync(queueName);

            SharedAccessAuthorizationRule rule;

            if (!description.Authorization.TryGetSharedAccessAuthorizationRule(ruleName, out rule))
            {
                throw new Exception($"Authorization rule {ruleName} was not found");
            }

            var address      = ServiceBusEnvironment.CreateServiceUri("sb", configuration.Find("Namespace"), string.Empty);
            var queueAddress = address + queueName;

            return(SharedAccessSignatureTokenProvider.GetSharedAccessSignature(ruleName, rule.PrimaryKey, queueAddress,
                                                                               TimeSpan.FromSeconds(int.Parse(configuration.Find("SignatureExpiration")))));
        }
Пример #22
0
        static async Task EventHubSendReceiveLoopAsync()
        {
            var connectionStringBuilder = new ServiceBusConnectionStringBuilder(connectionString)
            {
                EntityPath = eventhubName
            };

            var settings = new MessagingFactorySettings();

            settings.TransportType = Microsoft.ServiceBus.Messaging.TransportType.Amqp;
            settings.TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(connectionStringBuilder.SharedAccessKeyName, connectionStringBuilder.SharedAccessKey);
            var factory  = MessagingFactory.Create(connectionStringBuilder.Endpoints.FirstOrDefault <Uri>().ToString(), settings);
            var ehClient = factory.CreateEventHubClient(eventhubName);

            var sasTP = TokenProvider.CreateSharedAccessSignatureTokenProvider(connectionStringBuilder.SharedAccessKeyName, connectionStringBuilder.SharedAccessKey);
            var token = SharedAccessSignatureTokenProvider.GetSharedAccessSignature(connectionStringBuilder.SharedAccessKeyName, connectionStringBuilder.SharedAccessKey,
                                                                                    connectionStringBuilder.Endpoints.FirstOrDefault <Uri>().ToString(), TimeSpan.FromHours(12));

            await Task.WhenAll(
                SendMessagesRestAync($"https://{connectionStringBuilder.Endpoints.FirstOrDefault<Uri>().Host}/{connectionStringBuilder.EntityPath}", token)
                , ReceiveMessagesAsync(ehClient));
        }
Пример #23
0
        internal override bool Open(string entity)
        {
            if (this.Connection == null)
            {
                if (this.ServiceBusSecuritySettings.TokenProvider.GetType() == typeof(SharedAccessSignatureTokenProvider))
                {
                    SharedAccessSignatureTokenProvider tokenProvider = (SharedAccessSignatureTokenProvider)this.ServiceBusSecuritySettings.TokenProvider;
                    if ((tokenProvider.ShareAccessSignature != null) && (tokenProvider.ShareAccessSignature != string.Empty))
                    {
                        this.Connection = new Connection(this.amqpAddress, global::Amqp.Sasl.SaslProfile.External, null, null);

                        // send CBS token for the entity
                        return(this.PutCbsToken(tokenProvider.ShareAccessSignature, entity));
                    }
                    else
                    {
                        this.Connection = new Connection(this.amqpAddress);
                    }
                }
            }
            return(true);
        }
Пример #24
0
        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
                });
            }
        }
Пример #25
0
        static void Main(string[] args)
        {
            // example: https://namespace.servicebus.windows.net
            string ehNamespace = "namespace";

            // example: insights-telemetry-lad
            string eventHubName = "insights-telemetry-lad";

            // example: RootManageSharedAccessKey
            string hubPolicyName = "RootManageSharedAccessKey";

            // example: ZhLwp6lrVWQt5UFXXXXXXXXXXXXDuHWfY0J9RN1ctE=
            string hubPolicyKey = "your-policy-key";

            string resource = $"https://{ehNamespace}.servicebus.windows.net/{eventHubName}";

            string token = SharedAccessSignatureTokenProvider.GetSharedAccessSignature(
                hubPolicyName, hubPolicyKey,
                resource, new TimeSpan(365, 0, 0, 0));

            Console.WriteLine(token + "\r\n" + "Press any key");
            Console.ReadKey();
        }
 public HybridRelayHandler(RelayConfiguration relayConfig) : base()
 {
     _config        = relayConfig;
     _tokenProvider = new SharedAccessSignatureTokenProvider(_config.SasKeyName, _config.SasKey);
     InnerHandler   = new HttpClientHandler();
 }
Пример #27
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();
        }
Пример #28
0
        public string GenerateSharedAccessSignature()
        {
            var serviceUri = GetEventHubRestUri();

            return(SharedAccessSignatureTokenProvider.GetSharedAccessSignature(_connectionDetails.SharedAccessKeyName, _connectionDetails.SharedAccessKey, serviceUri, _tokenLifeTime));
        }
Пример #29
0
 public static string GetSas(string publisherId)
 {
     return(SharedAccessSignatureTokenProvider.GetPublisherSharedAccessSignature(new Uri(Namespace), EventHubName, publisherId, "Send", PrimaryKey, new TimeSpan(0, 5, 0)));
 }
Пример #30
0
        private static bool FactoryEquals(MessagingFactory factory1, MessagingFactory factory2)
        {
            bool flag;
            bool flag1;
            bool flag2;
            bool flag3;
            bool flag4;
            MessagingFactorySettings           settings      = factory1.GetSettings();
            SharedSecretTokenProvider          tokenProvider = settings.TokenProvider as SharedSecretTokenProvider;
            SharedAccessSignatureTokenProvider sharedAccessSignatureTokenProvider = settings.TokenProvider as SharedAccessSignatureTokenProvider;
            WindowsTokenProvider               windowsTokenProvider      = settings.TokenProvider as WindowsTokenProvider;
            OAuthTokenProvider                 oAuthTokenProvider        = settings.TokenProvider as OAuthTokenProvider;
            MessagingFactorySettings           messagingFactorySetting   = factory2.GetSettings();
            SharedSecretTokenProvider          sharedSecretTokenProvider = messagingFactorySetting.TokenProvider as SharedSecretTokenProvider;
            SharedAccessSignatureTokenProvider tokenProvider1            = messagingFactorySetting.TokenProvider as SharedAccessSignatureTokenProvider;
            WindowsTokenProvider               windowsTokenProvider1     = messagingFactorySetting.TokenProvider as WindowsTokenProvider;
            OAuthTokenProvider                 oAuthTokenProvider1       = messagingFactorySetting.TokenProvider as OAuthTokenProvider;

            if (settings.OperationTimeout != messagingFactorySetting.OperationTimeout)
            {
                return(false);
            }
            if (settings.TransportType != messagingFactorySetting.TransportType)
            {
                return(false);
            }
            if (tokenProvider != null || sharedSecretTokenProvider != null)
            {
                flag = (tokenProvider == null ? false : sharedSecretTokenProvider != null);
            }
            else
            {
                flag = true;
            }
            bool flag5 = flag;

            if (windowsTokenProvider != null || windowsTokenProvider1 != null)
            {
                flag1 = (windowsTokenProvider == null ? false : windowsTokenProvider1 != null);
            }
            else
            {
                flag1 = true;
            }
            bool flag6 = flag1;

            if (oAuthTokenProvider != null || oAuthTokenProvider1 != null)
            {
                flag2 = (oAuthTokenProvider == null ? false : oAuthTokenProvider1 != null);
            }
            else
            {
                flag2 = true;
            }
            bool flag7 = flag2;

            if (sharedAccessSignatureTokenProvider != null || tokenProvider1 != null)
            {
                flag3 = (sharedAccessSignatureTokenProvider == null ? false : tokenProvider1 != null);
            }
            else
            {
                flag3 = true;
            }
            bool flag8 = flag3;

            if (!flag5 || !flag6 || !flag7 || !flag8)
            {
                return(false);
            }
            if (tokenProvider != null && sharedSecretTokenProvider != null && (tokenProvider.IssuerName != sharedSecretTokenProvider.IssuerName || !tokenProvider.IssuerSecret.SequenceEqual <byte>(sharedSecretTokenProvider.IssuerSecret) || tokenProvider.IsWebTokenSupported != sharedSecretTokenProvider.IsWebTokenSupported))
            {
                return(false);
            }
            if (sharedAccessSignatureTokenProvider != null && tokenProvider1 != null)
            {
                if (sharedAccessSignatureTokenProvider.encodedSharedAccessKey != null || tokenProvider1.encodedSharedAccessKey != null)
                {
                    flag4 = (sharedAccessSignatureTokenProvider.encodedSharedAccessKey == null ? false : tokenProvider1.encodedSharedAccessKey != null);
                }
                else
                {
                    flag4 = true;
                }
                bool flag9 = flag4;
                if (sharedAccessSignatureTokenProvider.keyName != tokenProvider1.keyName || sharedAccessSignatureTokenProvider.tokenTimeToLive != tokenProvider1.tokenTimeToLive || !flag9)
                {
                    return(false);
                }
                if (sharedAccessSignatureTokenProvider.encodedSharedAccessKey != null && tokenProvider1.encodedSharedAccessKey != null)
                {
                    if ((int)sharedAccessSignatureTokenProvider.encodedSharedAccessKey.Length != (int)tokenProvider1.encodedSharedAccessKey.Length)
                    {
                        return(false);
                    }
                    if (!sharedAccessSignatureTokenProvider.encodedSharedAccessKey.SequenceEqual <byte>(tokenProvider1.encodedSharedAccessKey))
                    {
                        return(false);
                    }
                }
            }
            if (oAuthTokenProvider != null && oAuthTokenProvider1 != null && oAuthTokenProvider.IsWebTokenSupported != oAuthTokenProvider1.IsWebTokenSupported)
            {
                return(false);
            }
            if (windowsTokenProvider != null && windowsTokenProvider1 != null)
            {
                if (windowsTokenProvider.IsWebTokenSupported != windowsTokenProvider1.IsWebTokenSupported || windowsTokenProvider.stsUris.Count != windowsTokenProvider1.stsUris.Count)
                {
                    return(false);
                }
                if (windowsTokenProvider.stsUris.Where <Uri>((Uri t, int i) => t != windowsTokenProvider1.stsUris[i]).Any <Uri>())
                {
                    return(false);
                }
                if (windowsTokenProvider.credential == null && windowsTokenProvider1.credential != null || windowsTokenProvider.credential != null && windowsTokenProvider1.credential == null)
                {
                    return(false);
                }
                if (windowsTokenProvider.credential != null && windowsTokenProvider1.credential != null && (!windowsTokenProvider.credential.Domain.Equals(windowsTokenProvider1.credential.Domain, StringComparison.OrdinalIgnoreCase) || !windowsTokenProvider.credential.UserName.Equals(windowsTokenProvider1.credential.UserName, StringComparison.OrdinalIgnoreCase) || !windowsTokenProvider.credential.Password.Equals(windowsTokenProvider1.credential.Password)))
                {
                    return(false);
                }
            }
            return(factory1.Address == factory2.Address);
        }