예제 #1
0
        public void getSasKey()
        {
            try
            {
                // Create namespace manager.
                Uri              uri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, string.Empty);
                TokenProvider    td  = TokenProvider.CreateSharedAccessSignatureTokenProvider(namespaceManageKeyName, namespaceManageKey);
                NamespaceManager nm  = new NamespaceManager(uri, td);

                // Create event hub with a SAS rule that enables sending to that event hub
                EventHubDescription ed = new EventHubDescription(ehubname)
                {
                    PartitionCount = 32
                };
                string eventHubSendKeyName = "EventHubSendKey";
                string eventHubSendKey     = SharedAccessAuthorizationRule.GenerateRandomKey();
                SharedAccessAuthorizationRule eventHubSendRule = new SharedAccessAuthorizationRule
                                                                     (eventHubSendKeyName, eventHubSendKey, new[] { AccessRights.Send });
                ed.Authorization.Add(eventHubSendRule);
                nm.CreateEventHub(ed);
                string resource = "insightsehub.servicebus.windows.net/" + ehubname;

                //Copy this SAS Key for use in configuring the VM Diagnostics
                string saskey = SharedAccessSignatureTokenProvider.GetSharedAccessSignature(eventHubSendKeyName,
                                                                                            eventHubSendKey, resource, TimeSpan.FromDays(365));
                Console.WriteLine("Event HUb Endpoint created");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception " + ex.StackTrace);
            }
        }
예제 #2
0
        // This method rolls the primary key on a auth rule.
        public static void RollSharedAccessKeysOnEntity(string serviceNamespace, string qPath, string keyName, string key)
        {
            // Create an instance of NamespaceManager for the operation.
            Uri              managementUri = ServiceBusEnvironment.CreateServiceUri("https", serviceNamespace, string.Empty);
            TokenProvider    sasTP         = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyName, key);
            NamespaceManager nsm           = new NamespaceManager(managementUri, sasTP);

            // Get the queue description.
            QueueDescription qd = nsm.GetQueue(qPath);

            IEnumerator <AuthorizationRule> rulesEnumerator = qd.Authorization.GetEnumerator();

            while (rulesEnumerator.MoveNext())
            {
                SharedAccessAuthorizationRule typedRule = rulesEnumerator.Current as SharedAccessAuthorizationRule;
                if (typedRule != null) // Confirm that this is a 'SharedAccessAuthorizationRule'
                {
                    // Roll the keys.
                    // Note that this will also roll the keys on the 'contosoQManageRule' which is being used to
                    // authenticate this request, but since it won't take effect until we call NamespaceManager.UpdateQueue()
                    // that will still work.
                    typedRule.SecondaryKey = typedRule.PrimaryKey;
                    typedRule.PrimaryKey   = SharedAccessAuthorizationRule.GenerateRandomKey();
                }
            }
            // Apply the updated rules
            nsm.UpdateQueue(qd);
        }
예제 #3
0
        private static void CreateServiceBusQueue(string queueName)
        {
            var namespaceManager = NamespaceManager.CreateFromConnectionString(ConnectionStringForManaging);

            if (namespaceManager.QueueExists(queueName))
            {
                Console.WriteLine($"Queue '{queueName}' exists.");
                return;
            }

            var qd         = new QueueDescription(queueName);
            var sendKey    = SharedAccessAuthorizationRule.GenerateRandomKey();
            var receiveKey = SharedAccessAuthorizationRule.GenerateRandomKey();

            qd.Authorization.Add(new SharedAccessAuthorizationRule("SendKey", sendKey, new[] { AccessRights.Send }));
            qd.Authorization.Add(new SharedAccessAuthorizationRule("ReceiveKey", receiveKey, new[] { AccessRights.Listen }));

            namespaceManager.CreateQueue(qd);
            Console.WriteLine($"Created queue '{queueName}'.");

            Console.WriteLine($"Now manually update the App.config in the Queue Listening-Service with the Send and Receive connection strings for this Queue:'{queueName}'.");
            Console.WriteLine("Send Key - SharedAccessKeyName:'SendKey'");
            Console.WriteLine($"Send Key - SharedAccessKey:'{sendKey}'");
            Console.WriteLine();

            Console.WriteLine($"Receive Key - SharedAccessKeyName:'ReceiveKey'");
            Console.WriteLine($"Receive Key - SharedAccessKey:'{receiveKey}'");

            Console.WriteLine("Hit any key to continue...");
            Console.ReadKey(true);
        }
예제 #4
0
        public async Task <EventHubDescription> CreateEventHubAsync()
        {
            string serviceBusNamespace = "iotmc-ns";
            string serviceBusManageKey = "<< Add your SAS here >>";
            string eventHubName        = "IoTMC";
            string eventHubSASKeyName  = "Device01";

            Uri              serviceBusUri    = ServiceBusEnvironment.CreateServiceUri("sb", serviceBusNamespace, string.Empty);
            TokenProvider    tokenProvider    = TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", serviceBusManageKey);
            NamespaceManager nameSpaceManager = new NamespaceManager(string.Format("//{0}/", serviceBusUri.Host), tokenProvider);
            string           eventHubKey      = SharedAccessAuthorizationRule.GenerateRandomKey();

            EventHubDescription eventHubDescription = new EventHubDescription(eventHubName)
            {
                PartitionCount         = 8,
                MessageRetentionInDays = 1
            };
            SharedAccessAuthorizationRule eventHubSendRule = new SharedAccessAuthorizationRule(eventHubSASKeyName, eventHubKey, new[] { AccessRights.Send, AccessRights.Listen });

            eventHubDescription.Authorization.Add(eventHubSendRule);
            eventHubDescription = await nameSpaceManager.CreateEventHubIfNotExistsAsync(eventHubDescription);

            string eventHubSASKey = ((SharedAccessAuthorizationRule)eventHubDescription.Authorization.First()).PrimaryKey;

            return(eventHubDescription);
        }
예제 #5
0
        // This method will create a queue "sampleQueues/contosoQ" with 2 shared access authorization rules
        // for the Listen & Send rights. It uses SharedAccessSignature auth to create the queue and manage the
        // authorization rules for the queue.
        public static void CreateSASRuleOnEntity(string serviceNamespace, string qPath, string keyName, string key)
        {
            // Create an instance of NamespaceManager for the operation
            Uri              managementUri = ServiceBusEnvironment.CreateServiceUri("https", serviceNamespace, string.Empty);
            TokenProvider    sasTP         = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyName, key);
            NamespaceManager nsm           = new NamespaceManager(managementUri, sasTP);
            QueueDescription qd            = new QueueDescription(qPath);

            // Setup a rule with send rights with keyName as "contosoQSendKey"
            // and add it to the queue description.
            Program.contosoQSendRule = new SharedAccessAuthorizationRule("contosoQSendKey",
                                                                         SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                         new[] { AccessRights.Send });
            qd.Authorization.Add(Program.contosoQSendRule);

            // Setup a rule with listen rights with keyName as "contosoQListenKey"
            // and add it to the queue description.
            Program.contosoQListenRule = new SharedAccessAuthorizationRule("contosoQListenKey",
                                                                           SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                           new[] { AccessRights.Listen });
            qd.Authorization.Add(Program.contosoQListenRule);

            // Setup a rule with manage rights with keyName as "contosoQManageKey"
            // and add it to the queue description.
            // A rule with the Manage right MUST also have the Send & Receive rights.
            Program.contosoQManageRule = new SharedAccessAuthorizationRule("contosoQManageKey",
                                                                           SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                           new[] { AccessRights.Manage, AccessRights.Listen, AccessRights.Send });
            qd.Authorization.Add(Program.contosoQManageRule);

            // Create the queue.
            nsm.CreateQueue(qd);
        }
        public void RelayWithAuthorization()
        {
            string relayName = "RelayWithAuthorization";
            var    ns        = NamespaceManager.CreateFromConnectionString(TestServiceBus.relayConnectionString);

            try
            {
                var relayDescription = new RelayDescription(relayName, RelayType.Http)
                {
                    RequiresClientAuthorization = true,
                    RequiresTransportSecurity   = true
                };

                var sendKey       = SharedAccessAuthorizationRule.GenerateRandomKey();
                var sendKeyName   = "SendAccessKey";
                var listenKey     = SharedAccessAuthorizationRule.GenerateRandomKey();
                var listenKeyName = "ListenAccessKey";

                relayDescription.Authorization.Add(new SharedAccessAuthorizationRule(listenKeyName, listenKey,
                                                                                     new List <AccessRights> {
                    AccessRights.Listen
                }));
                relayDescription.Authorization.Add(new SharedAccessAuthorizationRule(sendKeyName, sendKey,
                                                                                     new List <AccessRights> {
                    AccessRights.Send
                }));

                ns.CreateRelay(relayDescription);
                Assert.IsTrue(ns.RelayExists(relayName));
            }
            finally
            {
                ns.DeleteRelay(relayName);
            }
        }
예제 #7
0
        /// <summary>
        /// Create connection in service bus name space
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        protected Task <string> CreateConnectionAsync(string name)
        {
#if NET45 || NET46
            var key     = SharedAccessAuthorizationRule.GenerateRandomKey();
            var putData =
                @"<entry xmlns=""http://www.w3.org/2005/Atom"">
                    <title type=""text"">" + name + @"</title>
                    <content type=""application/xml"">
                        <HybridConnectionDescription xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" 
                                xmlns=""http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"">
                            <RequiresClientAuthorization>true</RequiresClientAuthorization>
                            <AuthorizationRules>
                                <AuthorizationRule i:type=""SharedAccessAuthorizationRule"">
                                    <ClaimType>SharedAccessKey</ClaimType>
                                    <ClaimValue>None</ClaimValue>
                                    <Rights>
                                        <AccessRights>Send</AccessRights>
                                        <AccessRights>Listen</AccessRights>
                                    </Rights>
                                    <KeyName>proxy</KeyName>
                                    <PrimaryKey>" + key + @"</PrimaryKey>
                                </AuthorizationRule>
                            </AuthorizationRules>      
                        </HybridConnectionDescription>  
                    </content>
                </entry>";
            return(DoRequestAsync(GetManagementUri(name), HttpMethod.Put, putData));
#else
            throw new NotSupportedException("Must create relay entity first and specifiy in connection string");
#endif
        }
        public void HybridConnectionWithAuthorization()
        {
            string relayName = "HybridConnectionWithAuthorization";
            var    ns        = NamespaceManager.CreateFromConnectionString(TestServiceBus.relayConnectionString);

            try
            {
                //https://www.codit.eu/blog/2014/12/securing-azure-service-bus-relay-endpoints-with-sharedaccesssignatures/
                var relayDescription = new HybridConnectionDescription(relayName)
                {
                    RequiresClientAuthorization = true
                };

                var sendKey       = SharedAccessAuthorizationRule.GenerateRandomKey();
                var sendKeyName   = "SendAccessKey";
                var listenKey     = SharedAccessAuthorizationRule.GenerateRandomKey();
                var listenKeyName = "ListenAccessKey";

                relayDescription.Authorization.Add(new SharedAccessAuthorizationRule(listenKeyName, listenKey,
                                                                                     new List <AccessRights> {
                    AccessRights.Listen
                }));
                relayDescription.Authorization.Add(new SharedAccessAuthorizationRule(sendKeyName, sendKey,
                                                                                     new List <AccessRights> {
                    AccessRights.Send
                }));

                ns.CreateHybridConnection(relayDescription);
                Assert.IsTrue(ns.HybridConnectionExists(relayName));
            }
            finally
            {
                ns.DeleteHybridConnection(relayName);
            }
        }
예제 #9
0
        private static void CreateServiceBusTopic(string topicName)
        {
            var namespaceManager = NamespaceManager.CreateFromConnectionString(ConnectionStringForManaging);

            if (namespaceManager.TopicExists(topicName))
            {
                Console.WriteLine($"Topic '{topicName}' exists.");
                return;
            }

            var td         = new TopicDescription(topicName);
            var sendKey    = SharedAccessAuthorizationRule.GenerateRandomKey();
            var receiveKey = SharedAccessAuthorizationRule.GenerateRandomKey();

            td.Authorization.Add(new SharedAccessAuthorizationRule("SendKey", sendKey, new[] { AccessRights.Send }));
            td.Authorization.Add(new SharedAccessAuthorizationRule("ReceiveKey", receiveKey, new[] { AccessRights.Listen }));
            td.EnablePartitioning = true;
            namespaceManager.CreateTopic(td);
            Console.WriteLine($"Created Topic '{topicName}'.");

            Console.WriteLine($"Now manually update the App.config in the Subscription Listening-Service with the Send and Receive connection strings for this Topic:'{topicName}'.");
            Console.WriteLine("Send Key - SharedAccessKeyName:'SendKey'");
            Console.WriteLine($"Send Key - SharedAccessKey:'{sendKey}'");
            Console.WriteLine();

            Console.WriteLine($"Receive Key - SharedAccessKeyName:'ReceiveKey'");
            Console.WriteLine($"Receive Key - SharedAccessKey:'{receiveKey}'");

            Console.WriteLine("Hit any key to continue...");
            Console.ReadKey(true);
        }
예제 #10
0
        /// <summary>
        /// Updates shared access signature authorization for the service bus namespace. This authorization works on
        /// public Microsoft Azure environments and Windows Azure Pack on prim as well.
        /// </summary>
        /// <param name="namespaceName">The service bus namespace name</param>
        /// <param name="ruleName">The SAS authorization rule name</param>
        /// <param name="primaryKey">The SAS primary key. It'll be generated if empty</param>
        /// <param name="secondaryKey">The SAS secondary key</param>
        /// <param name="permissions">Set of permissions given to the rule</param>
        /// <returns>The created Shared Access Signature authorization rule</returns>
        public virtual ExtendedAuthorizationRule UpdateSharedAccessAuthorization(
            string namespaceName,
            string ruleName,
            string primaryKey,
            string secondaryKey,
            params AccessRights[] permissions)
        {
            ExtendedAuthorizationRule oldRule = GetAuthorizationRule(namespaceName, ruleName);

            if (null == oldRule)
            {
                throw new ArgumentException(Resources.ServiceBusAuthorizationRuleNotFound);
            }

            SharedAccessAuthorizationRule rule = (SharedAccessAuthorizationRule)oldRule.Rule;

            // Update the rule
            rule.Rights       = permissions ?? rule.Rights;
            rule.PrimaryKey   = string.IsNullOrEmpty(primaryKey) ? rule.PrimaryKey : primaryKey;
            rule.SecondaryKey = string.IsNullOrEmpty(secondaryKey) ? rule.SecondaryKey : secondaryKey;

            // In case that there's nothing to update then assume user asks for primary key renewal
            if (permissions == null && string.IsNullOrEmpty(secondaryKey) && string.IsNullOrEmpty(primaryKey))
            {
                rule.PrimaryKey = SharedAccessAuthorizationRule.GenerateRandomKey();
            }

            rule = ServiceBusClient.Namespaces.UpdateAuthorizationRule(
                namespaceName,
                rule.ToServiceBusSharedAccessAuthorizationRule())
                   .AuthorizationRule.ToSharedAccessAuthorizationRule();

            return(CreateExtendedAuthorizationRule(rule, namespaceName));
        }
예제 #11
0
        protected override void CreateTopic(NamespaceManager nsm)
        {
            if (nsm.TopicExists(topicName))
            {
                nsm.DeleteTopic(topicName);
            }

            if (!nsm.TopicExists(topicName))
            {
                // this topic will use Topic related Shared Access Keys
                TopicDescription td = new TopicDescription(topicName);

                // create a new SAS for topic
                tsKey = SharedAccessAuthorizationRule.GenerateRandomKey();
                td.Authorization.Add(new SharedAccessAuthorizationRule(tsKeyName, tsKey, new[] { AccessRights.Send }));
                tlKey = SharedAccessAuthorizationRule.GenerateRandomKey();
                td.Authorization.Add(new SharedAccessAuthorizationRule(tlKeyName, tlKey, new[] { AccessRights.Listen }));

                nsm.CreateTopic(td);
            }

            _tc = _cf.CreateTopicClient(nsName, topicName, tsKeyName, tsKey);


            if (!nsm.SubscriptionExists(topicName, topicSubName))
            {
                nsm.CreateSubscription(topicName, topicSubName);
            }
            _sc = _cf.CreateSubscriptionClient(nsName, topicName, topicSubName, tlKeyName, tlKey);
        }
예제 #12
0
    static void Main(string[] args)
    {
        string           serviceBusNamespace = "Please Provide Your ServiceBus Namespace";
        string           serviceBusManageKey = "Please Provide Your ServiceBus Shared Access Key";
        Uri              serviceBusUri       = ServiceBusEnvironment.CreateServiceUri("sb", serviceBusNamespace, string.Empty);
        TokenProvider    tokenProvider       = TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", serviceBusManageKey);
        NamespaceManager nameSpaceManager    = new NamespaceManager(string.Format("//{0}/", serviceBusUri.Host), tokenProvider);

        string eventHubName    = "EventHubCreatedWithCode";
        string eventHubKeyName = "EventHubKey";
        string eventHubKey     = SharedAccessAuthorizationRule.GenerateRandomKey();

        EventHubDescription eventHubDescription = new EventHubDescription(eventHubName)
        {
            PartitionCount = 8, MessageRetentionInDays = 1
        };
        SharedAccessAuthorizationRule eventHubSendRule = new SharedAccessAuthorizationRule(eventHubKeyName, eventHubKey, new[] { AccessRights.Send, AccessRights.Listen });

        eventHubDescription.Authorization.Add(eventHubSendRule);
        eventHubDescription = nameSpaceManager.CreateEventHubIfNotExists(eventHubDescription);
        string primaryKey = ((SharedAccessAuthorizationRule)eventHubDescription.Authorization.First()).PrimaryKey;

        Console.WriteLine("Primary Key: {0}", primaryKey);
        Console.ReadLine();
    }
        public static void CreateSASRuleOnNamespaceRoot(string subscriptionID, string managementCertSN, string serviceNamespace)
        {
            // The endpoint for creating a SAS rule on a namespace is:
            //     "https://management.core.windows.net/{subscriptionId}/services/ServiceBus/namespaces/{namespace}/AuthorizationRules/"
            string baseAddress = @"https://" + managementEndpoint + subscriptionID + @"/services/ServiceBus/namespaces/" +
                                 serviceNamespace + @"/AuthorizationRules/";

            // The SAS rule we'll create has keyName as "contosoSendAll, a base64 encoded 256-bit key and the Send right
            var sendRule = new SharedAccessAuthorizationRule("contosoSendAll",
                                                             SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                             new[] { AccessRights.Send });

            // Operations on the Service Bus namespace root require certificate authentication.
            WebRequestHandler handler = new WebRequestHandler
            {
                ClientCertificateOptions = ClientCertificateOption.Manual
            };

            handler.ClientCertificates.Add(GetCertificate(managementCertSN));

            HttpClient httpClient = new HttpClient(handler)
            {
                BaseAddress = new Uri(baseAddress)
            };

            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.DefaultRequestHeaders.Add("x-ms-version", "2012-03-01");

            // Do a POST on the baseAddress above to create an auth rule
            var postResult = httpClient.PostAsJsonAsync("", sendRule).Result;
        }
        static void Main(string[] args)
        {
            // The connection string for the RootManageSharedAccessKey can be accessed from the Azure portal
            // by selecting the SB namespace and clicking on "Connection Information"
            Console.Write("Enter your connection string for the RootManageSharedAccessKey for your Service Bus namespace: ");
            nsConnectionString = Console.ReadLine();

            ///////////////////////////////////////////////////////////////////////////////////////
            // Create a topic with a SAS Listen rule and an associated subscription
            ///////////////////////////////////////////////////////////////////////////////////////
            NamespaceManager nm = NamespaceManager.CreateFromConnectionString(nsConnectionString);

            contosoTListenRule = new SharedAccessAuthorizationRule("contosoTListenKey",
                                                                   SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                   new[] { AccessRights.Listen });
            TopicDescription td = new TopicDescription(topicPath);

            td.Authorization.Add(contosoTListenRule);
            nm.CreateTopic(td);
            nm.CreateSubscription(topicPath, subscriptionName);

            ///////////////////////////////////////////////////////////////////////////////////////
            // Send a message to the topic
            // Note that this uses the connection string for RootManageSharedAccessKey
            // configured on the namespace root
            ///////////////////////////////////////////////////////////////////////////////////////
            MessagingFactory sendMF      = MessagingFactory.CreateFromConnectionString(nsConnectionString);
            TopicClient      tc          = sendMF.CreateTopicClient(topicPath);
            BrokeredMessage  sentMessage = CreateHelloMessage();

            tc.Send(sentMessage);
            Console.WriteLine("Sent Hello message to topic: ID={0}, Body={1}.", sentMessage.MessageId, sentMessage.GetBody <string>());

            ///////////////////////////////////////////////////////////////////////////////////////
            // Generate a SAS token scoped to a subscription using the SAS rule with
            // a Listen right configured on the Topic & TTL of 1 day
            ///////////////////////////////////////////////////////////////////////////////////////
            ServiceBusConnectionStringBuilder csBuilder = new ServiceBusConnectionStringBuilder(nsConnectionString);
            IEnumerable <Uri> endpoints         = csBuilder.Endpoints;
            string            subscriptionUri   = endpoints.First <Uri>().ToString() + topicPath + "/subscriptions/" + subscriptionName;
            string            subscriptionToken = SASTokenGenerator.GetSASToken(subscriptionUri,
                                                                                contosoTListenRule.KeyName, contosoTListenRule.PrimaryKey, TimeSpan.FromDays(1));

            ///////////////////////////////////////////////////////////////////////////////////////
            // Use the SAS token scoped to a subscription to receive the messages
            ///////////////////////////////////////////////////////////////////////////////////////
            MessagingFactory   listenMF        = MessagingFactory.Create(endpoints, new StaticSASTokenProvider(subscriptionToken));
            SubscriptionClient sc              = listenMF.CreateSubscriptionClient(topicPath, subscriptionName);
            BrokeredMessage    receivedMessage = sc.Receive(TimeSpan.FromSeconds(10));

            Console.WriteLine("Received message from subscription: ID = {0}, Body = {1}.", receivedMessage.MessageId, receivedMessage.GetBody <string>());

            ///////////////////////////////////////////////////////////////////////////////////////
            // Clean-up
            ///////////////////////////////////////////////////////////////////////////////////////
            nm.DeleteTopic(topicPath);
        }
예제 #15
0
        public static void AddManagementPolicy(string eventHubConnectionString, string eventHubPath)
        {
            NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(eventHubConnectionString);
            var evenhubDesc = namespaceManager.GetEventHub(eventHubPath);

            string eventHubKey = SharedAccessAuthorizationRule.GenerateRandomKey();
            SharedAccessAuthorizationRule eventHubSendRule =
                new SharedAccessAuthorizationRule("all", eventHubKey, new[] { AccessRights.Send, AccessRights.Listen, AccessRights.Manage });

            evenhubDesc.Authorization.Add(eventHubSendRule);
            namespaceManager.UpdateEventHub(evenhubDesc);
        }
예제 #16
0
        /// <summary>
        /// Creates shared access signature authorization for the service bus entity. This authorization works on
        /// public Microsoft Azure environments and Windows Azure Pack on prim as well.
        /// </summary>
        /// <param name="namespaceName">The service bus namespace name</param>
        /// <param name="entityName">The fully qualified service bus entity name</param>
        /// <param name="entityType">The service bus entity type (e.g. Queue)</param>
        /// <param name="ruleName">The SAS authorization rule name</param>
        /// <param name="primaryKey">The SAS primary key. It'll be generated if empty</param>
        /// <param name="secondaryKey">The SAS secondary key</param>
        /// <param name="permissions">Set of permissions given to the rule</param>
        /// <returns>The created Shared Access Signature authorization rule</returns>
        public virtual ExtendedAuthorizationRule CreateSharedAccessAuthorization(
            string namespaceName,
            string entityName,
            ServiceBusEntityType entityType,
            string ruleName,
            string primaryKey,
            string secondaryKey,
            params AccessRights[] permissions)
        {
            // Create the SAS authorization rule
            SharedAccessAuthorizationRule rule = new SharedAccessAuthorizationRule(
                ruleName,
                string.IsNullOrEmpty(primaryKey) ? SharedAccessAuthorizationRule.GenerateRandomKey() : primaryKey,
                secondaryKey,
                permissions);

            // Create namespace manager
            NamespaceManager namespaceManager = CreateNamespaceManager(namespaceName);

            // Add the SAS rule and update the entity
            switch (entityType)
            {
            case ServiceBusEntityType.Queue:
                QueueDescription queue = namespaceManager.GetQueue(entityName);
                queue.Authorization.Add(rule);
                namespaceManager.UpdateQueue(queue);
                break;

            case ServiceBusEntityType.Topic:
                TopicDescription topic = namespaceManager.GetTopic(entityName);
                topic.Authorization.Add(rule);
                namespaceManager.UpdateTopic(topic);
                break;

            case ServiceBusEntityType.Relay:
                RelayDescription relay = namespaceManager.GetRelayAsync(entityName).Result;
                relay.Authorization.Add(rule);
                namespaceManager.UpdateRelayAsync(relay).Wait();
                break;

            case ServiceBusEntityType.NotificationHub:
                NotificationHubDescription notificationHub = namespaceManager.GetNotificationHub(entityName);
                notificationHub.Authorization.Add(rule);
                namespaceManager.UpdateNotificationHub(notificationHub);
                break;

            default:
                throw new Exception(string.Format(Resources.ServiceBusEntityTypeNotFound, entityType.ToString()));
            }

            return(CreateExtendedAuthorizationRule(rule, namespaceName, entityName, entityType));
        }
예제 #17
0
        private static void RegenerateKey(QueueDescription description, string ruleName, TextWriter log)
        {
            SharedAccessAuthorizationRule rule;

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

            rule.SecondaryKey = rule.PrimaryKey;
            rule.PrimaryKey   = SharedAccessAuthorizationRule.GenerateRandomKey();

            log.WriteLine($"Authorization rule: {ruleName}\nPrimary key: {rule.PrimaryKey}\nSecondary key: {rule.SecondaryKey}");
        }
예제 #18
0
        public static async Task <EventHubDescription> UpdateEventHub(string eventHubName, NamespaceManager namespaceManager)
        {
            // Add a consumer group
            EventHubDescription ehd = await namespaceManager.GetEventHubAsync(eventHubName);

            await namespaceManager.CreateConsumerGroupIfNotExistsAsync(ehd.Path, "consumerGroupName");

            // Create a customer SAS rule with Manage permissions
            ehd.UserMetadata = "Some updated info";
            string ruleName = "myeventhubmanagerule";
            string ruleKey  = SharedAccessAuthorizationRule.GenerateRandomKey();

            ehd.Authorization.Add(new SharedAccessAuthorizationRule(ruleName, ruleKey, new AccessRights[] { AccessRights.Manage, AccessRights.Listen, AccessRights.Send }));

            EventHubDescription ehdUpdated = await namespaceManager.UpdateEventHubAsync(ehd);

            return(ehd);
        }
예제 #19
0
        private static async void CreateHashForDevice(string deviceName, string eventHubName, string serviceBus)
        {
            string serviceBusConnectionString = Constants.GetBusConnectionString(serviceBus, "configure", Constants.ConsumerHash);
            var    connectionString           = new ServiceBusConnectionStringBuilder(serviceBusConnectionString);

            var namespaceManager = NamespaceManager.CreateFromConnectionString(serviceBusConnectionString);
            var ehd = await namespaceManager.GetEventHubAsync(eventHubName);

            // Create a customer SAS rule with Manage permissions
            ehd.UserMetadata = deviceName;
            string ruleName = deviceName;
            string ruleKey  = SharedAccessAuthorizationRule.GenerateRandomKey();

            ehd.Authorization.Add(new SharedAccessAuthorizationRule(ruleName, ruleKey, new AccessRights[] { AccessRights.Send }));
            namespaceManager.UpdateEventHubAsync(ehd).Wait();

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine(String.Format("{0} => {1}", deviceName, ruleKey));
        }
예제 #20
0
        private static void CreateServiceBusQueue(string queueName, bool requireSessions = false)
        {
            var namespaceManager = NamespaceManager.CreateFromConnectionString(ConnectionStringForManaging);

            if (namespaceManager.QueueExists(queueName))
            {
                if (namespaceManager.GetQueue(queueName).RequiresSession != requireSessions)
                {
                    Console.WriteLine($"Queue '{queueName}' will be deleted. Hit <enter> to confirm.");
                    Console.ReadLine();
                    namespaceManager.DeleteQueue(queueName);
                    Thread.Sleep(5);
                }
                else
                {
                    Console.WriteLine($"Queue '{queueName}' exists.");
                    return;
                }
            }

            var qd         = new QueueDescription(queueName);
            var sendKey    = SharedAccessAuthorizationRule.GenerateRandomKey();
            var receiveKey = SharedAccessAuthorizationRule.GenerateRandomKey();

            qd.Authorization.Add(new SharedAccessAuthorizationRule("SendKey", sendKey, new[] { AccessRights.Send }));
            qd.Authorization.Add(new SharedAccessAuthorizationRule("ReceiveKey", receiveKey, new[] { AccessRights.Listen }));
            qd.RequiresSession    = requireSessions;
            qd.EnablePartitioning = true;

            namespaceManager.CreateQueue(qd);
            Console.WriteLine($"Created queue '{queueName}'.");

            Console.WriteLine($"Now manually update the App.config in the Queue Listening-Service with the Send and Receive connection strings for this Queue:'{queueName}'.");
            Console.WriteLine("Send Key - SharedAccessKeyName:'SendKey'");
            Console.WriteLine($"Send Key - SharedAccessKey:'{sendKey}'");
            Console.WriteLine();

            Console.WriteLine($"Receive Key - SharedAccessKeyName:'ReceiveKey'");
            Console.WriteLine($"Receive Key - SharedAccessKey:'{receiveKey}'");

            Console.WriteLine("Hit any key to continue...");
            Console.ReadKey(true);
        }
예제 #21
0
        /// <summary>
        /// Creates new Windows authorization rule for Service Bus. This works on Windows Azure Pack on prim only.
        /// </summary>
        /// <param name="namespaceName">The service bus namespace name</param>
        /// <param name="ruleName">The authorization rule name</param>
        /// <param name="username">The user principle name</param>
        /// <param name="permissions">Set of permissions given to the rule</param>
        /// <returns>The created Windows authorization rule</returns>
        /// Comment for now we will need this part in the future when adding Katal Authentication Rules.
        //public virtual AllowRule CreateWindowsAuthorization(
        //    string namespaceName,
        //    string ruleName,
        //    string username,
        //    params AccessRights[] permissions)
        //{
        //    AllowRule rule = new AllowRule(
        //        string.Empty,
        //        "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn",
        //        username,
        //        permissions);

        //    using (HttpClient client = CreateServiceBusHttpClient())
        //    {
        //        rule = client.PostJson(UriElement.GetNamespaceAuthorizationRulesPath(namespaceName), rule, Logger);
        //    }

        //    return rule;
        //}

        /// <summary>
        /// Creates shared access signature authorization for the service bus namespace. This authorization works on
        /// public Microsoft Azure environments and Windows Azure Pack on prim as well.
        /// </summary>
        /// <param name="namespaceName">The service bus namespace name</param>
        /// <param name="ruleName">The SAS authorization rule name</param>
        /// <param name="primaryKey">The SAS primary key. It'll be generated if empty</param>
        /// <param name="secondaryKey">The SAS secondary key</param>
        /// <param name="permissions">Set of permissions given to the rule</param>
        /// <returns>The created Shared Access Signature authorization rule</returns>
        public virtual ExtendedAuthorizationRule CreateSharedAccessAuthorization(
            string namespaceName,
            string ruleName,
            string primaryKey,
            string secondaryKey,
            params AccessRights[] permissions)
        {
            SharedAccessAuthorizationRule rule = new SharedAccessAuthorizationRule(
                ruleName,
                string.IsNullOrEmpty(primaryKey) ? SharedAccessAuthorizationRule.GenerateRandomKey() : primaryKey,
                secondaryKey,
                permissions);

            rule = ServiceBusClient.Namespaces.CreateAuthorizationRule(
                namespaceName,
                rule.ToServiceBusSharedAccessAuthorizationRule())
                   .AuthorizationRule.ToSharedAccessAuthorizationRule();

            return(CreateExtendedAuthorizationRule(rule, namespaceName));
        }
예제 #22
0
        /// <summary>
        /// Creates shared access signature authorization for the service bus namespace. This authorization works on
        /// public Windows Azure environments and Windows Azure Pack on prim as well.
        /// </summary>
        /// <param name="namespaceName">The service bus namespace name</param>
        /// <param name="ruleName">The SAS authorization rule name</param>
        /// <param name="primaryKey">The SAS primary key. It'll be generated if empty</param>
        /// <param name="secondaryKey">The SAS secondary key</param>
        /// <param name="permissions">Set of permissions given to the rule</param>
        /// <returns>The created Shared Access Signature authorization rule</returns>
        public virtual ExtendedAuthorizationRule CreateSharedAccessAuthorization(
            string namespaceName,
            string ruleName,
            string primaryKey,
            string secondaryKey,
            params AccessRights[] permissions)
        {
            SharedAccessAuthorizationRule rule = new SharedAccessAuthorizationRule(
                ruleName,
                string.IsNullOrEmpty(primaryKey) ? SharedAccessAuthorizationRule.GenerateRandomKey() : primaryKey,
                secondaryKey,
                permissions);

            using (HttpClient client = CreateServiceBusHttpClient())
            {
                rule = client.PostJson(UriElement.GetNamespaceAuthorizationRulesPath(namespaceName), rule, Logger);
            }

            return(CreateExtendedAuthorizationRule(rule, namespaceName));
        }
예제 #23
0
        public async Task <EventHubDescription> CreateEventHubByConnectionStringAsync()
        {
            string eventHubName               = "IoTMC";
            string eventHubSASKeyName         = "Device01";
            string serviceBusConnectionString = "Endpoint=sb://iotmc-ns.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=<<Add your SAS here>>";

            NamespaceManager    nameSpaceManager    = NamespaceManager.CreateFromConnectionString(serviceBusConnectionString);
            string              eventHubKey         = SharedAccessAuthorizationRule.GenerateRandomKey();
            EventHubDescription eventHubDescription = new EventHubDescription(eventHubName)
            {
                PartitionCount         = 8,
                MessageRetentionInDays = 1
            };
            SharedAccessAuthorizationRule eventHubSendRule = new SharedAccessAuthorizationRule(eventHubSASKeyName, eventHubKey,
                                                                                               new[] { AccessRights.Send, AccessRights.Listen });

            eventHubDescription.Authorization.Add(eventHubSendRule);
            eventHubDescription = await nameSpaceManager.CreateEventHubIfNotExistsAsync(eventHubDescription);

            string eventHubSASKey = ((SharedAccessAuthorizationRule)eventHubDescription.Authorization.First()).PrimaryKey;

            return(eventHubDescription);
        }
        public static void RollSharedAccessKeyOnNamespaceRoot(string subscriptionID, string managementCertSN, string serviceNamespace, List <SharedAccessAuthorizationRule> rules)
        {
            // The endpoint for a SAS rules on the namespace is:
            //     "https://management.core.windows.net/{subscriptionId}/services/ServiceBus/namespaces/{namespace}/AuthorizationRules/"
            string baseAddress = @"https://" + managementEndpoint + subscriptionID + @"/services/ServiceBus/namespaces/" +
                                 serviceNamespace + @"/AuthorizationRules/";

            // Operations on the Service Bus namespace root require certificate authentication.
            WebRequestHandler handler = new WebRequestHandler
            {
                ClientCertificateOptions = ClientCertificateOption.Manual
            };

            handler.ClientCertificates.Add(GetCertificate(managementCertSN));

            HttpClient httpClient = new HttpClient(handler)
            {
                BaseAddress = new Uri(baseAddress)
            };

            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.DefaultRequestHeaders.Add("x-ms-version", "2012-03-01");

            rules.ForEach(delegate(SharedAccessAuthorizationRule rule)
            {
                // Roll keys on all rules except the "RootManageSharedAccessKey"
                if (!String.Equals(rule.KeyName, "RootManageSharedAccessKey", StringComparison.Ordinal))
                {
                    rule.SecondaryKey = rule.PrimaryKey;
                    rule.PrimaryKey   = SharedAccessAuthorizationRule.GenerateRandomKey();

                    // Update the rule
                    var putResult = httpClient.PutAsJsonAsync(rule.KeyName, rule).Result;
                }
            });
        }
예제 #25
0
        private void btnCreateDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (serviceBusHelper == null)
                {
                    return;
                }
                if (btnCreateDelete.Text == DeleteText)
                {
                    using (var deleteForm = new DeleteForm(eventHubDescription.Path, EventHubEntity.ToLower()))
                    {
                        if (deleteForm.ShowDialog() == DialogResult.OK)
                        {
                            serviceBusHelper.DeleteEventHub(eventHubDescription);
                        }
                    }
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(txtPath.Text))
                    {
                        writeToLog(PathCannotBeNull);
                        return;
                    }
                    var description = new EventHubDescription(txtPath.Text)
                    {
                        UserMetadata = txtUserMetadata.Text
                    };

                    description.MessageRetentionInDays = trackBarMessageRetentionInDays.Value;

                    description.PartitionCount = trackBarPartitionCount.Value;

                    var bindingList = authorizationRulesBindingSource.DataSource as BindingList <AuthorizationRuleWrapper>;
                    if (bindingList != null)
                    {
                        for (var i = 0; i < bindingList.Count; i++)
                        {
                            var rule = bindingList[i];
                            if (serviceBusHelper.IsCloudNamespace)
                            {
                                if (string.IsNullOrWhiteSpace(rule.KeyName))
                                {
                                    writeToLog(string.Format(KeyNameCannotBeNull, i));
                                    continue;
                                }
                            }
                            var rightList = new List <AccessRights>();
                            if (rule.Manage)
                            {
                                rightList.AddRange(new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen });
                            }
                            else
                            {
                                if (rule.Send)
                                {
                                    rightList.Add(AccessRights.Send);
                                }
                                if (rule.Listen)
                                {
                                    rightList.Add(AccessRights.Listen);
                                }
                            }
                            if (serviceBusHelper.IsCloudNamespace)
                            {
                                if (string.IsNullOrWhiteSpace(rule.SecondaryKey))
                                {
                                    description.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                    rule.PrimaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                    rightList));
                                }
                                else
                                {
                                    description.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                    rule.PrimaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                    rule.SecondaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                    rightList));
                                }
                            }
                            else
                            {
                                description.Authorization.Add(new AllowRule(rule.IssuerName,
                                                                            rule.ClaimType,
                                                                            rule.ClaimValue,
                                                                            rightList));
                            }
                        }
                    }

                    eventHubDescription = serviceBusHelper.CreateEventHub(description);
                    InitializeControls();
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
예제 #26
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();
        }
예제 #27
0
        // ReSharper disable once FunctionComplexityOverflow
        private async void btnCreateDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (serviceBusHelper == null)
                {
                    return;
                }
                if (btnCreateDelete.Text == DeleteText)
                {
                    using (var deleteForm = new DeleteForm(relayDescription.Path, RelayEntity.ToLower()))
                    {
                        if (deleteForm.ShowDialog() == DialogResult.OK)
                        {
                            await serviceBusHelper.NamespaceManager.DeleteRelayAsync(relayDescription.Path);

                            //serviceBusHelper.DeleteRelay(relayDescription.Path);
                        }
                    }
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(txtPath.Text))
                    {
                        writeToLog(PathCannotBeNull);
                        return;
                    }
                    var description = new RelayDescription(txtPath.Text, (RelayType)Enum.Parse(typeof(RelayType), cboRelayType.Text, true))
                    {
                        UserMetadata = txtUserMetadata.Text,
                        RequiresClientAuthorization = checkedListBox.GetItemChecked(RequiresClientAuthorizationIndex),
                        RequiresTransportSecurity   = checkedListBox.GetItemChecked(RequiresTransportSecurityIndex)
                    };

                    var bindingList = authorizationRulesBindingSource.DataSource as BindingList <AuthorizationRuleWrapper>;
                    if (bindingList != null)
                    {
                        for (var i = 0; i < bindingList.Count; i++)
                        {
                            var rule = bindingList[i];
                            if (serviceBusHelper.IsCloudNamespace)
                            {
                                if (string.IsNullOrWhiteSpace(rule.KeyName))
                                {
                                    writeToLog(string.Format(KeyNameCannotBeNull, i));
                                    continue;
                                }
                            }
                            var rightList = new List <AccessRights>();
                            if (rule.Manage)
                            {
                                rightList.AddRange(new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen });
                            }
                            else
                            {
                                if (rule.Send)
                                {
                                    rightList.Add(AccessRights.Send);
                                }
                                if (rule.Listen)
                                {
                                    rightList.Add(AccessRights.Listen);
                                }
                            }
                            if (serviceBusHelper.IsCloudNamespace)
                            {
                                if (string.IsNullOrWhiteSpace(rule.SecondaryKey))
                                {
                                    description.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                    rule.PrimaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                    rightList));
                                }
                                else
                                {
                                    description.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                    rule.PrimaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                    rule.SecondaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                    rightList));
                                }
                            }
                            else
                            {
                                description.Authorization.Add(new AllowRule(rule.IssuerName,
                                                                            rule.ClaimType,
                                                                            rule.ClaimValue,
                                                                            rightList));
                            }
                        }
                    }
                    relayDescription = serviceBusHelper.CreateRelay(description);
                    InitializeControls();
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
        private async void StartDevices()
        {
            // Create namespace manager
            var namespaceUri     = ServiceBusEnvironment.CreateServiceUri("sb", txtNamespace.Text, string.Empty);
            var tokenProvider    = TokenProvider.CreateSharedAccessSignatureTokenProvider(txtKeyName.Text, txtKeyValue.Text);
            var namespaceManager = new NamespaceManager(namespaceUri, tokenProvider);

            // Check if the event hub already exists, if not, create the event hub.
            if (!await namespaceManager.EventHubExistsAsync(cboEventHub.Text))
            {
                WriteToLog(string.Format(EventHubDoesNotExists, cboEventHub.Text));
                return;
            }
            var eventHubDescription = await namespaceManager.GetEventHubAsync(cboEventHub.Text);

            WriteToLog(string.Format(EventHubCreatedOrRetrieved, cboEventHub.Text));

            // Check if the SAS authorization rule used by devices to send events to the event hub already exists, if not, create the rule.
            var authorizationRule = eventHubDescription.
                                    Authorization.
                                    FirstOrDefault(r => string.Compare(r.KeyName,
                                                                       SenderSharedAccessKey,
                                                                       StringComparison.InvariantCultureIgnoreCase)
                                                   == 0) as SharedAccessAuthorizationRule;

            if (authorizationRule == null)
            {
                authorizationRule = new SharedAccessAuthorizationRule(SenderSharedAccessKey,
                                                                      SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                      new[]
                {
                    AccessRights.Send
                });
                eventHubDescription.Authorization.Add(authorizationRule);
                await namespaceManager.UpdateEventHubAsync(eventHubDescription);
            }

            cancellationTokenSource = new CancellationTokenSource();
            var serviceBusNamespace = txtNamespace.Text;
            var eventHubName        = cboEventHub.Text;
            var senderKey           = authorizationRule.PrimaryKey;
            var status            = DefaultStatus;
            var eventInterval     = txtEventIntervalInMilliseconds.IntegerValue;
            var minValue          = txtMinValue.IntegerValue;
            var maxValue          = txtMaxValue.IntegerValue;
            var minOffset         = txtMinOffset.IntegerValue;
            var maxOffset         = txtMaxOffset.IntegerValue;
            var spikePercentage   = trackbarSpikePercentage.Value;
            var cancellationToken = cancellationTokenSource.Token;

            // Create one task for each device
            for (var i = 1; i <= txtDeviceCount.IntegerValue; i++)
            {
                var deviceId = i;
#pragma warning disable 4014
#pragma warning disable 4014
                Task.Run(async() =>
#pragma warning restore 4014
                {
                    var deviceName = $"device{deviceId:000}";

                    if (radioButtonAmqp.Checked)
                    {
                        // The token has the following format:
                        // SharedAccessSignature sr={URI}&sig={HMAC_SHA256_SIGNATURE}&se={EXPIRATION_TIME}&skn={KEY_NAME}
                        var token = CreateSasTokenForAmqpSender(SenderSharedAccessKey,
                                                                senderKey,
                                                                serviceBusNamespace,
                                                                eventHubName,
                                                                deviceName,
                                                                TimeSpan.FromDays(1));
                        WriteToLog(string.Format(SasToken, deviceId));

                        var messagingFactory = MessagingFactory.Create(ServiceBusEnvironment.CreateServiceUri("sb", serviceBusNamespace, ""), new MessagingFactorySettings
                        {
                            TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(token),
                            TransportType = TransportType.Amqp
                        });
                        WriteToLog(string.Format(MessagingFactoryCreated, deviceId));

                        // Each device uses a different publisher endpoint: [EventHub]/publishers/[PublisherName]
                        var eventHubClient = messagingFactory.CreateEventHubClient($"{eventHubName}/publishers/{deviceName}");
                        WriteToLog(string.Format(EventHubClientCreated, deviceId, eventHubClient.Path));

                        while (!cancellationToken.IsCancellationRequested)
                        {
                            // Create random value
                            var value     = GetValue(minValue, maxValue, minOffset, maxOffset, spikePercentage);
                            var timestamp = DateTime.Now;

                            // Create EventData object with the payload serialized in JSON format
                            var payload = new Payload
                            {
                                DeviceId  = deviceId,
                                Name      = deviceName,
                                Status    = status,
                                Value     = value,
                                Timestamp = timestamp
                            };
                            var json = JsonConvert.SerializeObject(payload);
                            using (var eventData = new EventData(Encoding.UTF8.GetBytes(json))
                            {
                                PartitionKey = deviceName
                            })
                            {
                                // Create custom properties
                                eventData.Properties.Add(DeviceId, deviceId);
                                eventData.Properties.Add(DeviceName, deviceName);
                                eventData.Properties.Add(DeviceStatus, status);
                                eventData.Properties.Add(Value, value);
                                eventData.Properties.Add(Timestamp, timestamp);

                                // Send the event to the event hub
                                await eventHubClient.SendAsync(eventData);
                                WriteToLog($"[Event] DeviceId=[{payload.DeviceId:000}] " +
                                           $"Value=[{payload.Value:000}] " +
                                           $"Timestamp=[{payload.Timestamp}]");
                            }

                            // Wait for the event time interval
                            Thread.Sleep(eventInterval);
                        }
                    }
                    else
                    {
                        // The token has the following format:
                        // SharedAccessSignature sr={URI}&sig={HMAC_SHA256_SIGNATURE}&se={EXPIRATION_TIME}&skn={KEY_NAME}
                        var token = CreateSasTokenForHttpsSender(SenderSharedAccessKey,
                                                                 senderKey,
                                                                 serviceBusNamespace,
                                                                 eventHubName,
                                                                 deviceName,
                                                                 TimeSpan.FromDays(1));
                        WriteToLog(string.Format(SasToken, deviceId));

                        // Create HttpClient object used to send events to the event hub.
                        var httpClient = new HttpClient
                        {
                            BaseAddress =
                                new Uri(string.Format(EventHubUrl,
                                                      serviceBusNamespace,
                                                      eventHubName,
                                                      deviceName).ToLower())
                        };
                        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", token);
                        httpClient.DefaultRequestHeaders.Add("ContentType",
                                                             "application/json;type=entry;charset=utf-8");
                        WriteToLog(string.Format(HttpClientCreated, deviceId, httpClient.BaseAddress));

                        while (!cancellationToken.IsCancellationRequested)
                        {
                            // Create random value
                            var value     = GetValue(minValue, maxValue, minOffset, maxOffset, spikePercentage);
                            var timestamp = DateTime.Now;

                            // Create EventData object with the payload serialized in JSON format
                            var payload = new Payload
                            {
                                DeviceId  = deviceId,
                                Name      = deviceName,
                                Status    = status,
                                Value     = value,
                                Timestamp = timestamp
                            };
                            var json = JsonConvert.SerializeObject(payload);

                            // Create HttpContent
                            var postContent = new ByteArrayContent(Encoding.UTF8.GetBytes(json));

                            // Create custom properties
                            postContent.Headers.Add(DeviceId, deviceId.ToString(CultureInfo.InvariantCulture));
                            postContent.Headers.Add(DeviceName, deviceName);
                            //postContent.Headers.Add(DeviceStatus, location);
                            postContent.Headers.Add(Value, value.ToString(CultureInfo.InvariantCulture));
                            postContent.Headers.Add(Timestamp, timestamp.ToString(CultureInfo.InvariantCulture));

                            try
                            {
                                var response =
                                    await
                                    httpClient.PostAsync(
                                        httpClient.BaseAddress + "/messages" + "?timeout=60" + ApiVersion,
                                        postContent, cancellationToken);
                                response.EnsureSuccessStatusCode();
                                WriteToLog($"[Event] DeviceId=[{payload.DeviceId:000}] " +
                                           $"Value=[{payload.Value:000}] " +
                                           $"Timestamp=[{payload.Timestamp}]");
                            }
                            catch (HttpRequestException ex)
                            {
                                WriteToLog(string.Format(SendFailed, deviceId, ex.Message));
                            }

                            // Wait for the event time interval
                            Thread.Sleep(eventInterval);
                        }
                    }
                },
                         cancellationToken).ContinueWith(t =>
#pragma warning restore 4014
#pragma warning restore 4014
                {
                    if (t.IsFaulted && t.Exception != null)
                    {
                        HandleException(t.Exception);
                    }
                }, cancellationToken);
            }
        }
예제 #29
0
        // ReSharper disable once FunctionComplexityOverflow
        private void btnCancelUpdate_Click(object sender, EventArgs e)
        {
            if (btnCancelUpdate.Text == CancelText)
            {
                if (OnCancel != null)
                {
                    OnCancel();
                }
            }
            else
            {
                try
                {
                    relayDescription.UserMetadata = txtUserMetadata.Text;

                    var bindingList = authorizationRulesBindingSource.DataSource as BindingList <AuthorizationRuleWrapper>;
                    if (bindingList != null)
                    {
                        for (var i = 0; i < bindingList.Count; i++)
                        {
                            var rule = bindingList[i];

                            if (serviceBusHelper.IsCloudNamespace)
                            {
                                if (string.IsNullOrWhiteSpace(rule.KeyName))
                                {
                                    writeToLog(string.Format(KeyNameCannotBeNull, i));
                                    continue;
                                }
                            }
                            var rightList = new List <AccessRights>();
                            if (rule.Manage)
                            {
                                rightList.AddRange(new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen });
                            }
                            else
                            {
                                if (rule.Send)
                                {
                                    rightList.Add(AccessRights.Send);
                                }
                                if (rule.Listen)
                                {
                                    rightList.Add(AccessRights.Listen);
                                }
                            }
                            if (serviceBusHelper.IsCloudNamespace)
                            {
                                if (string.IsNullOrWhiteSpace(rule.PrimaryKey) && string.IsNullOrWhiteSpace(rule.SecondaryKey))
                                {
                                    relayDescription.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                         rightList));
                                }
                                else if (string.IsNullOrWhiteSpace(rule.SecondaryKey))
                                {
                                    relayDescription.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                         rule.PrimaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                         rightList));
                                }
                                else
                                {
                                    relayDescription.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                         rule.PrimaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                         rule.SecondaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                         rightList));
                                }
                            }
                            else
                            {
                                relayDescription.Authorization.Add(new AllowRule(rule.IssuerName,
                                                                                 rule.ClaimType,
                                                                                 rule.ClaimValue,
                                                                                 rightList));
                            }
                        }
                    }
                    relayDescription = serviceBusHelper.UpdateRelay(relayDescription);
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                    relayDescription = serviceBusHelper.GetRelay(relayDescription.Path);
                }
                finally
                {
                    InitializeControls();
                }
            }
        }
예제 #30
0
        /// <summary>
        /// Updates shared access signature authorization for the service bus entity. This authorization works on
        /// public Windows Azure environments and Windows Azure Pack on prim as well.
        /// </summary>
        /// <param name="namespaceName">The service bus namespace name</param>
        /// <param name="entityName">The fully qualified service bus entity name</param>
        /// <param name="entityType">The service bus entity type (e.g. Queue)</param>
        /// <param name="ruleName">The SAS authorization rule name</param>
        /// <param name="primaryKey">The SAS primary key. It'll be generated if empty</param>
        /// <param name="secondaryKey">The SAS secondary key</param>
        /// <param name="permissions">Set of permissions given to the rule</param>
        /// <returns>The created Shared Access Signature authorization rule</returns>
        public ExtendedAuthorizationRule UpdateSharedAccessAuthorization(
            string namespaceName,
            string entityName,
            ServiceBusEntityType entityType,
            string ruleName,
            string primaryKey,
            string secondaryKey,
            params AccessRights[] permissions)
        {
            bool removed = false;
            ExtendedAuthorizationRule rule = GetAuthorizationRule(namespaceName, entityName, entityType, ruleName);

            if (null == rule)
            {
                throw new ArgumentException(Resources.ServiceBusAuthorizationRuleNotFound);
            }

            SharedAccessAuthorizationRule oldRule = (SharedAccessAuthorizationRule)rule.Rule;

            SharedAccessAuthorizationRule newRule = new SharedAccessAuthorizationRule(
                ruleName,
                string.IsNullOrEmpty(primaryKey) ? SharedAccessAuthorizationRule.GenerateRandomKey() : primaryKey,
                secondaryKey,
                permissions ?? oldRule.Rights);

            // Create namespace manager
            NamespaceManager namespaceManager = CreateNamespaceManager(namespaceName);

            // Add the SAS rule and update the entity
            switch (entityType)
            {
            case ServiceBusEntityType.Queue:
                QueueDescription queue = namespaceManager.GetQueue(entityName);
                removed = queue.Authorization.Remove(oldRule);
                Debug.Assert(removed);
                queue.Authorization.Add(newRule);
                namespaceManager.UpdateQueue(queue);
                break;

            case ServiceBusEntityType.Topic:
                TopicDescription topic = namespaceManager.GetTopic(entityName);
                removed = topic.Authorization.Remove(oldRule);
                Debug.Assert(removed);
                topic.Authorization.Add(newRule);
                namespaceManager.UpdateTopic(topic);
                break;

            case ServiceBusEntityType.Relay:
                RelayDescription relay = namespaceManager.GetRelayAsync(entityName).Result;
                removed = relay.Authorization.Remove(oldRule);
                Debug.Assert(removed);
                relay.Authorization.Add(newRule);
                namespaceManager.UpdateRelayAsync(relay).Wait();
                break;

            case ServiceBusEntityType.NotificationHub:
                NotificationHubDescription notificationHub = namespaceManager.GetNotificationHub(entityName);
                removed = notificationHub.Authorization.Remove(oldRule);
                Debug.Assert(removed);
                notificationHub.Authorization.Add(newRule);
                namespaceManager.UpdateNotificationHub(notificationHub);
                break;

            default:
                throw new Exception(string.Format(Resources.ServiceBusEntityTypeNotFound, entityType.ToString()));
            }

            return(CreateExtendedAuthorizationRule(newRule, namespaceName, entityName, entityType));
        }