示例#1
0
        public void GetIdentityTest()
        {
            // Arrange
            var amqpValue = new AmqpValue
            {
                Value = TokenHelper.CreateSasToken("edgehubtest1.azure-devices.net/devices/device1/modules/mod1")
            };
            AmqpMessage validAmqpMessage = AmqpMessage.Create(amqpValue);

            validAmqpMessage.ApplicationProperties.Map[CbsConstants.PutToken.Type]     = "azure-devices.net:sastoken";
            validAmqpMessage.ApplicationProperties.Map[CbsConstants.PutToken.Audience] = "iothub";
            validAmqpMessage.ApplicationProperties.Map[CbsConstants.Operation]         = CbsConstants.PutToken.OperationValue;

            var clientCredentials = Mock.Of <IClientCredentials>();
            var identityFactory   = new Mock <IClientCredentialsFactory>();

            identityFactory.Setup(i => i.GetWithSasToken(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
            .Returns(clientCredentials);

            string iotHubHostName = "edgehubtest1.azure-devices.net";
            var    authenticator  = new Mock <IAuthenticator>();
            var    cbsNode        = new CbsNode(identityFactory.Object, iotHubHostName, authenticator.Object, new NullCredentialsStore());

            // Act
            IClientCredentials receivedClientCredentials = cbsNode.GetClientCredentials(validAmqpMessage);

            // Assert
            Assert.NotNull(receivedClientCredentials);
            Assert.Equal(clientCredentials, receivedClientCredentials);
        }
示例#2
0
        public void GetClientTokenTest()
        {
            // Arrange
            var amqpValue = new AmqpValue
            {
                Value = TokenHelper.CreateSasToken("edgehubtest1.azure-devices.net/devices/device1/modules/mod1")
            };
            AmqpMessage validAmqpMessage = AmqpMessage.Create(amqpValue);

            validAmqpMessage.ApplicationProperties.Map[CbsConstants.PutToken.Type]     = "azure-devices.net:sastoken";
            validAmqpMessage.ApplicationProperties.Map[CbsConstants.PutToken.Audience] = "edgehubtest1.azure-devices.net/devices/device1/modules/mod1";
            validAmqpMessage.ApplicationProperties.Map[CbsConstants.Operation]         = CbsConstants.PutToken.OperationValue;

            var    identityFactory = new Mock <IClientCredentialsFactory>();
            string iotHubHostName  = "edgehubtest1.azure-devices.net";
            var    authenticator   = new Mock <IAuthenticator>();
            var    cbsNode         = new CbsNode(identityFactory.Object, iotHubHostName, authenticator.Object, new NullCredentialsCache());

            // Act
            CbsNode.ClientToken clientToken = cbsNode.GetClientToken(validAmqpMessage);

            // Assert
            Assert.NotNull(clientToken);
            Assert.Equal("device1/mod1", clientToken.Id);
            Assert.Equal(amqpValue.Value, clientToken.Token);
        }
示例#3
0
        public object GetObject()
        {
            RestrictedDescribed body = amqpMessage.BodySection;

            if (body == null)
            {
                return(null);
            }
            else if (body is AmqpValue)
            {
                AmqpValue value = body as AmqpValue;
                return(value.Value);
            }
            else if (body is Data)
            {
                return((body as Data).Binary);
            }
            else if (body is AmqpSequence)
            {
                return((body as AmqpSequence).List);
            }
            else
            {
                throw new IllegalStateException("Unexpected body type: " + body.GetType().Name);
            }
        }
示例#4
0
        static T GetValue <T>(this AmqpValue value)
        {
            ByteBuffer buffer = value.ValueBuffer;

            if (buffer == null)
            {
                return((T)value.Value);
            }

            buffer.Seek(0);
            if (typeof(T) == typeof(ByteBuffer))
            {
                int offset  = GetBinaryOffset(buffer);
                int len     = buffer.Length - offset;
                var payload = new ByteBuffer(buffer.Buffer, buffer.Offset + offset, len, len);
                return((T)(object)payload);
            }
            else if (typeof(T) == typeof(byte[]))
            {
                int    offset  = GetBinaryOffset(buffer);
                int    len     = buffer.Length - offset;
                byte[] payload = new byte[len];
                Buffer.BlockCopy(buffer.Buffer, buffer.Offset + offset, payload, 0, payload.Length);
                return((T)(object)payload);
            }
            else
            {
                return(AmqpSerializer.Deserialize <T>(buffer));
            }
        }
示例#5
0
        private static AmqpMessage CreateAmqpMessageFromSbmpMessage(BrokeredMessage brokeredMessage)
        {
            AmqpMessage amqpMessage;
            object      obj  = brokeredMessage.ClearBodyObject();
            object      obj1 = null;

            if (obj != null)
            {
                MessageConverter.TryGetAmqpObjectFromNetObject(obj, MappingType.MessageBody, out obj1);
            }
            if (obj1 != null)
            {
                AmqpValue amqpValue = new AmqpValue()
                {
                    Value = obj1
                };
                amqpMessage = AmqpMessage.Create(amqpValue);
            }
            else if (brokeredMessage.BodyStream == null)
            {
                amqpMessage = AmqpMessage.Create();
            }
            else
            {
                if (brokeredMessage.BodyStream.CanSeek && brokeredMessage.BodyStream.Position != (long)0)
                {
                    throw new InvalidOperationException(SRClient.CannotSerializeMessageWithPartiallyConsumedBodyStream);
                }
                amqpMessage = AmqpMessage.Create(brokeredMessage.BodyStream, false);
            }
            return(amqpMessage);
        }
示例#6
0
            protected override IEnumerator <IteratorAsyncResult <AmqpCbsLink.SendTokenAsyncResult> .AsyncStep> GetAsyncSteps()
            {
                string str;

                AmqpCbsLink.SendTokenAsyncResult sendTokenAsyncResult = this;
                IteratorAsyncResult <AmqpCbsLink.SendTokenAsyncResult> .BeginCall beginCall = (AmqpCbsLink.SendTokenAsyncResult thisPtr, TimeSpan t, AsyncCallback c, object s) => thisPtr.tokenProvider.BeginGetMessagingToken(this.namespaceAddress, thisPtr.resource, thisPtr.requiredClaims[0], false, t, c, s);
                yield return(sendTokenAsyncResult.CallAsync(beginCall, (AmqpCbsLink.SendTokenAsyncResult thisPtr, IAsyncResult r) => thisPtr.swt = (SimpleWebSecurityToken)thisPtr.tokenProvider.EndGetMessagingToken(r), IteratorAsyncResult <TIteratorAsyncResult> .ExceptionPolicy.Transfer));

                if (this.swt is SharedAccessSignatureToken)
                {
                    str = "servicebus.windows.net:sastoken";
                }
                else if (this.swt != null)
                {
                    str = "amqp:swt";
                }
                else
                {
                    str = null;
                }
                string str1 = str;

                if (str1 != null)
                {
                    if (!this.cbsLink.FaultTolerantLink.TryGetOpenedObject(out this.requestResponseLink))
                    {
                        AmqpCbsLink.SendTokenAsyncResult sendTokenAsyncResult1 = this;
                        IteratorAsyncResult <AmqpCbsLink.SendTokenAsyncResult> .BeginCall beginCall1 = (AmqpCbsLink.SendTokenAsyncResult thisPtr, TimeSpan t, AsyncCallback c, object s) => thisPtr.cbsLink.FaultTolerantLink.BeginGetInstance(t, c, s);
                        yield return(sendTokenAsyncResult1.CallAsync(beginCall1, (AmqpCbsLink.SendTokenAsyncResult thisPtr, IAsyncResult r) => thisPtr.requestResponseLink = thisPtr.cbsLink.FaultTolerantLink.EndGetInstance(r), IteratorAsyncResult <TIteratorAsyncResult> .ExceptionPolicy.Transfer));
                    }
                    AmqpValue amqpValue = new AmqpValue()
                    {
                        Value = this.swt.Token
                    };
                    AmqpMessage applicationProperty = AmqpMessage.Create(amqpValue);
                    applicationProperty.ApplicationProperties = new ApplicationProperties();
                    applicationProperty.ApplicationProperties.Map["operation"]  = "put-token";
                    applicationProperty.ApplicationProperties.Map["type"]       = str1;
                    applicationProperty.ApplicationProperties.Map["name"]       = this.audience;
                    applicationProperty.ApplicationProperties.Map["expiration"] = this.swt.ExpiresOn;
                    AmqpMessage amqpMessage = null;
                    yield return(base.CallAsync((AmqpCbsLink.SendTokenAsyncResult thisPtr, TimeSpan t, AsyncCallback c, object s) => this.requestResponseLink.BeginRequest(applicationProperty, t, c, s), (AmqpCbsLink.SendTokenAsyncResult thisPtr, IAsyncResult r) => amqpMessage = this.requestResponseLink.EndRequest(r), IteratorAsyncResult <TIteratorAsyncResult> .ExceptionPolicy.Transfer));

                    int    item  = (int)amqpMessage.ApplicationProperties.Map["status-code"];
                    string item1 = (string)amqpMessage.ApplicationProperties.Map["status-description"];
                    if (item != 202)
                    {
                        base.Complete(AmqpCbsLink.SendTokenAsyncResult.ConvertToException(item, item1));
                    }
                    else
                    {
                        this.ValidTo = this.swt.ValidTo;
                    }
                }
                else
                {
                    base.Complete(new InvalidOperationException(SRAmqp.AmqpUnssuportedTokenType));
                }
            }
示例#7
0
        static AmqpMessage CreateCommandMessage(IAmqpSerializable command)
        {
            AmqpValue value = new AmqpValue {
                Value = command
            };

            return(AmqpMessage.Create(value));
        }
        protected override void InitializeEmptyBody()
        {
            Map       amqpMap = new Map();
            AmqpValue val     = new AmqpValue {
                Value = amqpMap
            };

            map = new AMQPValueMap(amqpMap);
            Message.BodySection = val;
        }
示例#9
0
        void Convert_Amqp_message_with_Amqp_value_array_segment_to_SB_message()
        {
            var messageBody = Encoding.UTF8.GetBytes("message1");

            var amqpValue = new AmqpValue();

            amqpValue.Value = new ArraySegment <byte>(messageBody);
            var amqpMessage = AmqpMessage.Create(amqpValue);

            var sbMessage = AmqpMessageConverter.AmqpMessageToSBMessage(amqpMessage);

            Assert.Equal(messageBody, sbMessage.Body);
        }
示例#10
0
        void Convert_Amqp_message_with_Amqp_value_byte_array_to_SB_message()
        {
            var messageBody = Encoding.UTF8.GetBytes("message1");

            var amqpValue = new AmqpValue();

            amqpValue.Value = messageBody;
            var amqpMessage = AmqpMessage.Create(amqpValue);

            var sbMessage = AmqpMessageConverter.AmqpMessageToSBMessage(amqpMessage);

            Assert.Equal(messageBody, sbMessage.GetBody <byte[]>(null));
        }
示例#11
0
        public void MessageReader()
        {
            var value = new AmqpValue()
            {
                Value      = "ABC",
                Descriptor = "DEF"
            };

            var message = AmqpMessage.Create(value);
            //message.Header.Durable = true;

            var payload = message.GetPayload();
        }
示例#12
0
        public void ValidateTestThrowsOnInvalidOperation()
        {
            // Arrange
            var amqpValue = new AmqpValue
            {
                Value = TokenHelper.CreateSasToken(IoTHubHostName)
            };
            AmqpMessage invalidAmqpMessage3 = AmqpMessage.Create(amqpValue);

            invalidAmqpMessage3.ApplicationProperties.Map[CbsConstants.PutToken.Type]     = "azure-devices.net:sastoken";
            invalidAmqpMessage3.ApplicationProperties.Map[CbsConstants.PutToken.Audience] = "iothub";
            invalidAmqpMessage3.ApplicationProperties.Map[CbsConstants.Operation]         = "foobar";
            // Act/Assert
            Assert.Throws <InvalidOperationException>(() => CbsNode.ValidateAndParseMessage(IoTHubHostName, invalidAmqpMessage3));
        }
示例#13
0
        public void PeekedMessageShouldNotIncrementDeliveryCount()
        {
            var messageBody = Encoding.UTF8.GetBytes("message1");

            var amqpValue = new AmqpValue();

            amqpValue.Value = new ArraySegment <byte>(messageBody);
            var amqpMessage = AmqpMessage.Create(amqpValue);

            amqpMessage.Header.DeliveryCount = 2;

            var sbMessage = AmqpMessageConverter.AmqpMessageToSBMessage(amqpMessage, isPeeked: true);

            sbMessage.SequenceNumber = 1L;

            Assert.AreEqual(2, sbMessage.DeliveryCount);
        }
示例#14
0
        void When_message_is_received_should_have_delivery_count_increased()
        {
            var messageBody = Encoding.UTF8.GetBytes("message1");

            var amqpValue = new AmqpValue();

            amqpValue.Value = new ArraySegment <byte>(messageBody);
            var amqpMessage = AmqpMessage.Create(amqpValue);

            amqpMessage.Header.DeliveryCount = 2;

            var sbMessage = AmqpMessageConverter.AmqpMessageToSBMessage(amqpMessage, isPeeked: false);

            sbMessage.SystemProperties.SequenceNumber = 1L;

            Assert.Equal(3, sbMessage.SystemProperties.DeliveryCount);
        }
示例#15
0
        public async Task OnBehalfOfAuthTest()
        {
            // Arrange
            var amqpValue = new AmqpValue
            {
                Value = TokenHelper.CreateSasToken("edgehubtest1.azure-devices.net/devices/edge1/modules/$edgeHub")
            };
            AmqpMessage validAmqpMessage = AmqpMessage.Create(amqpValue);

            validAmqpMessage.ApplicationProperties.Map[CbsConstants.PutToken.Type]     = "azure-devices.net:sastoken";
            validAmqpMessage.ApplicationProperties.Map[CbsConstants.PutToken.Audience] = "edgehubtest1.azure-devices.net/devices/edge1/modules/$edgeHub";
            validAmqpMessage.ApplicationProperties.Map[CbsConstants.Operation]         = CbsConstants.PutToken.OperationValue;
            Option <string> authChain = Option.Some("device1;edge1");

            var actorEdgeHubIdentity     = Mock.Of <IIdentity>(i => i.Id == "edge1/$edgeHub");
            var clientCredentials        = Mock.Of <IClientCredentials>(c => c.Identity == actorEdgeHubIdentity && c.AuthChain == authChain);
            var clientCredentialsFactory = new Mock <IClientCredentialsFactory>();

            clientCredentialsFactory.Setup(i => i.GetWithSasToken(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), true, It.IsAny <Option <string> >(), It.Is <Option <string> >(chain => chain == authChain)))
            .Returns(clientCredentials);

            string iotHubHostName = "edgehubtest1.azure-devices.net";
            var    authenticator  = new Mock <IAuthenticator>();

            authenticator.Setup(a => a.AuthenticateAsync(It.Is <IClientCredentials>(cred => cred == clientCredentials))).ReturnsAsync(true);
            var cbsNode = new CbsNode(clientCredentialsFactory.Object, iotHubHostName, authenticator.Object, new NullCredentialsCache());

            // Act
            (AmqpResponseStatusCode statusCode, string description) = await cbsNode.UpdateCbsToken(validAmqpMessage);

            bool isAuthenticated = await cbsNode.AuthenticateAsync("device1", Option.None <string>(), authChain);

            // Auth again, we should still succeed even with the wrong credentials due to cached auth state
            (statusCode, description) = await cbsNode.UpdateCbsToken(validAmqpMessage);

            bool isReauthenticated = await cbsNode.AuthenticateAsync("device1", Option.None <string>(), Option.Some("not;valid;authchain"));

            // Assert
            Assert.True(isAuthenticated);
            Assert.Equal(AmqpResponseStatusCode.OK, statusCode);
            Assert.Equal(AmqpResponseStatusCode.OK.ToString(), description);
        }
示例#16
0
        void CopyFrom(AmqpMessage source, bool deepCopy, bool includeBody)
        {
            if (deepCopy)
            {
                this.DeepCopy(source);
            }
            else
            {
                this.ShadowCopy(source);
            }

            if (includeBody)
            {
                this.dataList      = source.dataList;
                this.sequenceList  = source.sequenceList;
                this.amqpValue     = source.amqpValue;
                this.bodyOffset    = source.bodyOffset;
                this.bodyLength    = source.bodyLength;
                this.sectionFlags |= (source.sectionFlags & SectionFlag.Body);
            }
        }
示例#17
0
        public void ValidateTestSucceeds()
        {
            // Arrange
            string sasToken  = TokenHelper.CreateSasToken(IoTHubHostName);
            var    amqpValue = new AmqpValue
            {
                Value = sasToken
            };
            AmqpMessage validAmqpMessage = AmqpMessage.Create(amqpValue);

            validAmqpMessage.ApplicationProperties.Map[CbsConstants.PutToken.Type]     = "azure-devices.net:sastoken";
            validAmqpMessage.ApplicationProperties.Map[CbsConstants.PutToken.Audience] = "iothub";
            validAmqpMessage.ApplicationProperties.Map[CbsConstants.Operation]         = CbsConstants.PutToken.OperationValue;

            // Act
            (string token, string audience) = CbsNode.ValidateAndParseMessage(IoTHubHostName, validAmqpMessage);

            // Assert
            Assert.Equal(sasToken, token);
            Assert.Equal(IoTHubHostName, audience);
        }
 private void InitializeMapBody()
 {
     if (message.BodySection == null)
     {
         amqpmap = new Map();
         map     = new AMQPValueMap(amqpmap);
         AmqpValue val = new AmqpValue();
         val.Value           = amqpmap;
         message.BodySection = val;
     }
     else
     {
         if (message.BodySection is AmqpValue)
         {
             object obj = (message.BodySection as AmqpValue).Value;
             if (obj == null)
             {
                 amqpmap = new Map();
                 map     = new AMQPValueMap(amqpmap);
                 (message.BodySection as AmqpValue).Value = amqpmap;
             }
             else if (obj is Map)
             {
                 amqpmap = obj as Map;
                 map     = new AMQPValueMap(amqpmap);
             }
             else
             {
                 throw new NMSException(string.Format("Invalid message body value type. Type: {0}.", obj.GetType().Name));
             }
         }
         else
         {
             throw new NMSException("Invalid message body type.");
         }
     }
 }
            protected override IEnumerator <IteratorAsyncResult <AmqpSubscriptionClient.RuleAsyncResult> .AsyncStep> GetAsyncSteps()
            {
                if (!this.client.controlLink.TryGetOpenedObject(out this.amqpLink))
                {
                    AmqpSubscriptionClient.RuleAsyncResult ruleAsyncResult = this;
                    IteratorAsyncResult <AmqpSubscriptionClient.RuleAsyncResult> .BeginCall beginCall = (AmqpSubscriptionClient.RuleAsyncResult thisPtr, TimeSpan t, AsyncCallback c, object s) => thisPtr.client.controlLink.BeginGetInstance(t, c, s);
                    yield return(ruleAsyncResult.CallAsync(beginCall, (AmqpSubscriptionClient.RuleAsyncResult thisPtr, IAsyncResult r) => thisPtr.amqpLink = thisPtr.client.controlLink.EndGetInstance(r), IteratorAsyncResult <TIteratorAsyncResult> .ExceptionPolicy.Transfer));
                }
                AmqpValue amqpValue = new AmqpValue()
                {
                    Value = this.CreateCommand()
                };
                AmqpMessage amqpMessage = AmqpMessage.Create(amqpValue);

                amqpMessage.Batchable = false;
                AmqpSubscriptionClient.RuleAsyncResult ruleAsyncResult1 = this;
                IteratorAsyncResult <AmqpSubscriptionClient.RuleAsyncResult> .BeginCall beginCall1 = (AmqpSubscriptionClient.RuleAsyncResult thisPtr, TimeSpan t, AsyncCallback c, object s) => thisPtr.amqpLink.BeginSendMessage(amqpMessage, thisPtr.client.GetControlMessageDeliveryTag(), new ArraySegment <byte>(), t, c, s);
                yield return(ruleAsyncResult1.CallAsync(beginCall1, (AmqpSubscriptionClient.RuleAsyncResult thisPtr, IAsyncResult r) => thisPtr.outcome = thisPtr.amqpLink.EndSendMessage(r), IteratorAsyncResult <TIteratorAsyncResult> .ExceptionPolicy.Transfer));

                if (this.outcome.DescriptorCode == Rejected.Code)
                {
                    base.Complete(ExceptionHelper.ToMessagingContract(((Rejected)this.outcome).Error));
                }
            }
示例#20
0
        public async Task UpdateCbsTokenTest()
        {
            // Arrange
            var amqpValue = new AmqpValue
            {
                Value = TokenHelper.CreateSasToken("edgehubtest1.azure-devices.net/devices/device1/modules/mod1")
            };
            AmqpMessage validAmqpMessage = AmqpMessage.Create(amqpValue);

            validAmqpMessage.ApplicationProperties.Map[CbsConstants.PutToken.Type]     = "azure-devices.net:sastoken";
            validAmqpMessage.ApplicationProperties.Map[CbsConstants.PutToken.Audience] = "iothub";
            validAmqpMessage.ApplicationProperties.Map[CbsConstants.Operation]         = CbsConstants.PutToken.OperationValue;

            var identity                 = Mock.Of <IIdentity>(i => i.Id == "device1/mod1");
            var clientCredentials        = Mock.Of <IClientCredentials>(c => c.Identity == identity);
            var clientCredentialsFactory = new Mock <IClientCredentialsFactory>();

            clientCredentialsFactory.Setup(i => i.GetWithSasToken(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
            .Returns(clientCredentials);

            string iotHubHostName = "edgehubtest1.azure-devices.net";
            var    authenticator  = new Mock <IAuthenticator>();

            authenticator.Setup(a => a.AuthenticateAsync(It.IsAny <IClientCredentials>())).ReturnsAsync(true);
            var cbsNode = new CbsNode(clientCredentialsFactory.Object, iotHubHostName, authenticator.Object, new NullCredentialsStore());

            // Act
            (AmqpAuthentication amqpAuthentication, AmqpResponseStatusCode statusCode, string description) = await cbsNode.UpdateCbsToken(validAmqpMessage);

            // Assert
            Assert.Equal(true, amqpAuthentication.IsAuthenticated);
            Assert.True(amqpAuthentication.ClientCredentials.HasValue);
            Assert.Equal(identity, amqpAuthentication.ClientCredentials.OrDefault().Identity);
            Assert.Equal(AmqpResponseStatusCode.OK, statusCode);
            Assert.Equal(AmqpResponseStatusCode.OK.ToString(), description);
        }
示例#21
0
 /// <summary>
 /// Creates a message with an AmqpValue as the body.
 /// </summary>
 /// <param name="value"></param>
 /// <returns>An AmqpMessage.</returns>
 public static AmqpMessage Create(AmqpValue value)
 {
     return(new AmqpValueMessage(value));
 }
示例#22
0
 public AmqpValueMessage(AmqpValue value)
 {
     this.amqpValue     = value;
     this.sectionFlags |= SectionFlag.AmqpValue;
 }
示例#23
0
            protected override IEnumerator <AsyncStep> GetAsyncSteps()
            {
                Task <CbsToken> getTokenTask = null;

                yield return(this.CallTask(
                                 (thisPtr, t) => getTokenTask = thisPtr.tokenProvider.GetTokenAsync(thisPtr.namespaceAddress, thisPtr.resource, thisPtr.requiredClaims),
                                 ExceptionPolicy.Transfer));

                this.token = getTokenTask.Result;

                string tokenType = this.token.TokenType;

                if (tokenType == null)
                {
                    this.Complete(new InvalidOperationException(AmqpResources.AmqpUnsupportedTokenType));
                    yield break;
                }

                RequestResponseAmqpLink requestResponseLink;

                if (this.cbsLink.linkFactory.TryGetOpenedObject(out requestResponseLink))
                {
                    this.requestResponseLinkTask = Task.FromResult(requestResponseLink);
                }
                else
                {
                    yield return(this.CallTask(
                                     (thisPtr, t) => thisPtr.requestResponseLinkTask = thisPtr.cbsLink.linkFactory.GetOrCreateAsync(t),
                                     ExceptionPolicy.Transfer));
                }

                AmqpValue value = new AmqpValue();

                value.Value = this.token.TokenValue;
                AmqpMessage putTokenRequest = AmqpMessage.Create(value);

                putTokenRequest.ApplicationProperties = new ApplicationProperties();
                putTokenRequest.ApplicationProperties.Map[CbsConstants.Operation]           = CbsConstants.PutToken.OperationValue;
                putTokenRequest.ApplicationProperties.Map[CbsConstants.PutToken.Type]       = tokenType;
                putTokenRequest.ApplicationProperties.Map[CbsConstants.PutToken.Audience]   = this.audience;
                putTokenRequest.ApplicationProperties.Map[CbsConstants.PutToken.Expiration] = this.token.ExpiresAtUtc;

                AmqpMessage putTokenResponse = null;

                Fx.AssertIsNotNull(this.requestResponseLinkTask.Result, "requestResponseLink cannot be null without exception");
                yield return(this.CallAsync(
                                 (thisPtr, t, c, s) => thisPtr.requestResponseLinkTask.Result.BeginRequest(putTokenRequest, t, c, s),
                                 (thisPtr, r) => putTokenResponse = thisPtr.requestResponseLinkTask.Result.EndRequest(r),
                                 ExceptionPolicy.Transfer));

                int    statusCode        = (int)putTokenResponse.ApplicationProperties.Map[CbsConstants.PutToken.StatusCode];
                string statusDescription = (string)putTokenResponse.ApplicationProperties.Map[CbsConstants.PutToken.StatusDescription];

                if (statusCode == (int)AmqpResponseStatusCode.Accepted || statusCode == (int)AmqpResponseStatusCode.OK)
                {
                    this.ExpiresAtUtc = this.token.ExpiresAtUtc;
                }
                else
                {
                    this.Complete(ConvertToException(statusCode, statusDescription));
                }
            }
示例#24
0
        /// <summary>
        /// Sends a security token for a resource for later access.
        /// </summary>
        /// <param name="tokenProvider">The provider for issuing security tokens.</param>
        /// <param name="namespaceAddress">The namespace (or tenant) name.</param>
        /// <param name="audience">The audience. In most cases it is the same as resource.</param>
        /// <param name="resource">The resource to access.</param>
        /// <param name="requiredClaims">The required claims to access the resource.</param>
        /// <param name="timeout">The operation timeout.</param>
        /// <returns></returns>
        public async Task <DateTime> SendTokenAsync(ICbsTokenProvider tokenProvider, Uri namespaceAddress, string audience, string resource, string[] requiredClaims, TimeSpan timeout)
        {
            if (this.connection.IsClosing())
            {
                throw new OperationCanceledException("Connection is closing or closed.");
            }

            CbsToken token = await tokenProvider.GetTokenAsync(namespaceAddress, resource, requiredClaims).ConfigureAwait(false);

            string tokenType = token.TokenType;

            if (tokenType == null)
            {
                throw new NotSupportedException(AmqpResources.AmqpUnsupportedTokenType);
            }

            RequestResponseAmqpLink requestResponseLink;

            if (!this.linkFactory.TryGetOpenedObject(out requestResponseLink))
            {
                requestResponseLink = await this.linkFactory.GetOrCreateAsync(timeout).ConfigureAwait(false);
            }

            AmqpValue value = new AmqpValue();

            value.Value = token.TokenValue;
            AmqpMessage putTokenRequest = AmqpMessage.Create(value);

            putTokenRequest.ApplicationProperties.Map[CbsConstants.Operation]           = CbsConstants.PutToken.OperationValue;
            putTokenRequest.ApplicationProperties.Map[CbsConstants.PutToken.Type]       = tokenType;
            putTokenRequest.ApplicationProperties.Map[CbsConstants.PutToken.Audience]   = audience;
            putTokenRequest.ApplicationProperties.Map[CbsConstants.PutToken.Expiration] = token.ExpiresAtUtc;

            AmqpMessage putTokenResponse = await requestResponseLink.RequestAsync(putTokenRequest, timeout).ConfigureAwait(false);

            int    statusCode        = (int)putTokenResponse.ApplicationProperties.Map[CbsConstants.PutToken.StatusCode];
            string statusDescription = (string)putTokenResponse.ApplicationProperties.Map[CbsConstants.PutToken.StatusDescription];

            if (statusCode == (int)AmqpResponseStatusCode.Accepted || statusCode == (int)AmqpResponseStatusCode.OK)
            {
                return(token.ExpiresAtUtc);
            }

            Exception exception;
            AmqpResponseStatusCode amqpResponseStatusCode = (AmqpResponseStatusCode)statusCode;

            switch (amqpResponseStatusCode)
            {
            case AmqpResponseStatusCode.BadRequest:
                exception = new AmqpException(AmqpErrorCode.InvalidField, AmqpResources.GetString(AmqpResources.AmqpPutTokenFailed, statusCode, statusDescription));
                break;

            case AmqpResponseStatusCode.NotFound:
                exception = new AmqpException(AmqpErrorCode.NotFound, AmqpResources.GetString(AmqpResources.AmqpPutTokenFailed, statusCode, statusDescription));
                break;

            case AmqpResponseStatusCode.Forbidden:
                exception = new AmqpException(AmqpErrorCode.TransferLimitExceeded, AmqpResources.GetString(AmqpResources.AmqpPutTokenFailed, statusCode, statusDescription));
                break;

            case AmqpResponseStatusCode.Unauthorized:
                exception = new AmqpException(AmqpErrorCode.UnauthorizedAccess, AmqpResources.GetString(AmqpResources.AmqpPutTokenFailed, statusCode, statusDescription));
                break;

            default:
                exception = new AmqpException(AmqpErrorCode.InvalidField, AmqpResources.GetString(AmqpResources.AmqpPutTokenFailed, statusCode, statusDescription));
                break;
            }

            throw exception;
        }