示例#1
0
        public override void OnOutgoingMessage(Message message, System.ServiceModel.Channels.RequestContext requestContext)
        {
            ContextMessageProperty         property;
            CallbackContextMessageProperty property2;

            if (message == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
            }
            if (ContextMessageProperty.TryGet(message, out property))
            {
                if (base.ContextExchangeMechanism == ContextExchangeMechanism.HttpCookie)
                {
                    Uri requestUri = null;
                    if (requestContext.RequestMessage.Properties != null)
                    {
                        requestUri = requestContext.RequestMessage.Properties.Via;
                    }
                    if (requestUri == null)
                    {
                        requestUri = requestContext.RequestMessage.Headers.To;
                    }
                    this.OnSendHttpCookies(message, property, requestUri);
                }
                else
                {
                    base.OnSendSoapContextHeader(message, property);
                }
            }
            if (CallbackContextMessageProperty.TryGet(message, out property2))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(System.ServiceModel.SR.GetString("CallbackContextNotExpectedOnOutgoingMessageAtServer", new object[] { message.Headers.Action })));
            }
        }
        private ContextMessageProperty OnReceiveHttpCookies(Message message)
        {
            ContextMessageProperty context = null;
            object obj2;

            if (message.Properties.TryGetValue(HttpResponseMessageProperty.Name, out obj2))
            {
                HttpResponseMessageProperty property2 = obj2 as HttpResponseMessageProperty;
                if (property2 == null)
                {
                    return(context);
                }
                string str = property2.Headers[HttpResponseHeader.SetCookie];
                if (string.IsNullOrEmpty(str))
                {
                    return(context);
                }
                lock (this.cookieContainer)
                {
                    if (!string.IsNullOrEmpty(str))
                    {
                        this.cookieContainer.SetCookies(this.Uri, str);
                        ContextProtocol.HttpCookieToolbox.TryCreateFromHttpCookieHeader(str, out context);
                    }
                    if (!this.contextManagementEnabled)
                    {
                        this.cookieContainer.SetCookies(this.Uri, "WscContext;Max-Age=0");
                    }
                }
            }
            return(context);
        }
示例#3
0
        ContextMessageProperty OnReceiveHttpCookies(Message message)
        {
            ContextMessageProperty newContext = null;
            object property;

            if (message.Properties.TryGetValue(HttpResponseMessageProperty.Name, out property))
            {
                HttpResponseMessageProperty httpResponse = property as HttpResponseMessageProperty;
                if (httpResponse != null)
                {
                    string setCookieHeader = httpResponse.Headers[HttpResponseHeader.SetCookie];

                    if (!string.IsNullOrEmpty(setCookieHeader))
                    {
                        lock (this.cookieContainer)
                        {
                            if (!string.IsNullOrEmpty(setCookieHeader))
                            {
                                this.cookieContainer.SetCookies(this.Uri, setCookieHeader);
                                HttpCookieToolbox.TryCreateFromHttpCookieHeader(setCookieHeader, out newContext);
                            }

                            if (!this.contextManagementEnabled)
                            {
                                this.cookieContainer.SetCookies(this.Uri, HttpCookieToolbox.RemoveContextHttpCookieHeader);
                            }
                        }
                    }
                }
            }
            return(newContext);
        }
        public override void OnIncomingMessage(Message message)
        {
            if (message == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
            }
            ContextMessageProperty newContext = null;

            if (base.ContextExchangeMechanism == ContextExchangeMechanism.HttpCookie)
            {
                newContext = this.OnReceiveHttpCookies(message);
            }
            else
            {
                newContext = this.OnReceiveSoapContextHeader(message);
            }
            if (newContext != null)
            {
                if (this.contextManagementEnabled)
                {
                    this.EnsureInvariants(true, newContext);
                }
                else
                {
                    newContext.AddOrReplaceInMessage(message);
                }
            }
            if (message.Headers.FindHeader("CallbackContext", "http://schemas.microsoft.com/ws/2008/02/context") != -1)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new ProtocolException(System.ServiceModel.SR.GetString("CallbackContextNotExpectedOnIncomingMessageAtClient", new object[] { message.Headers.Action, "CallbackContext", "http://schemas.microsoft.com/ws/2008/02/context" })));
            }
        }
示例#5
0
            public static string EncodeContextAsHttpSetCookieHeader(ContextMessageProperty context, Uri uri)
            {
                if (uri == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("uri");
                }
                if (context == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
                }

                MemoryStream      stream         = new MemoryStream();
                XmlWriterSettings writerSettings = new XmlWriterSettings();

                writerSettings.OmitXmlDeclaration = true;
                XmlWriter            writer        = XmlWriter.Create(stream, writerSettings);
                ContextMessageHeader contextHeader = new ContextMessageHeader(context.Context);

                contextHeader.WriteHeader(writer, MessageVersion.Default);
                writer.Flush();

                string result = string.Format(
                    CultureInfo.InvariantCulture,
                    "{0}=\"{1}\";Path={2}",
                    HttpCookieToolbox.ContextHttpCookieName,
                    Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length),
                    uri.AbsolutePath);

                return(result);
            }
            public static string EncodeContextAsHttpSetCookieHeader(ContextMessageProperty context, Uri uri)
            {
                if (uri == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("uri");
                }
                if (context == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
                }

                MemoryStream stream = new MemoryStream();
                XmlWriterSettings writerSettings = new XmlWriterSettings();
                writerSettings.OmitXmlDeclaration = true;
                XmlWriter writer = XmlWriter.Create(stream, writerSettings);
                ContextMessageHeader contextHeader = new ContextMessageHeader(context.Context);
                contextHeader.WriteHeader(writer, MessageVersion.Default);
                writer.Flush();

                string result = string.Format(
                    CultureInfo.InvariantCulture,
                    "{0}=\"{1}\";Path={2}",
                    HttpCookieToolbox.ContextHttpCookieName,
                    Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length),
                    uri.AbsolutePath);

                return result;
            }
 public static bool TryGet(Message message, out ContextMessageProperty contextMessageProperty)
 {
     if (message == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
     }
     return TryGet(message.Properties, out contextMessageProperty);
 }
示例#8
0
 public static bool TryGet(Message message, out ContextMessageProperty contextMessageProperty)
 {
     if (message == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
     }
     return(TryGet(message.Properties, out contextMessageProperty));
 }
 private string GetCookieHeaderFromContext(ContextMessageProperty contextMessageProperty)
 {
     if (contextMessageProperty.Context.Count == 0)
     {
         return("WscContext;Max-Age=0");
     }
     return(ContextProtocol.HttpCookieToolbox.EncodeContextAsHttpSetCookieHeader(contextMessageProperty, this.Uri));
 }
 private string GetCookieHeaderFromContext(ContextMessageProperty contextMessageProperty)
 {
     if (contextMessageProperty.Context.Count == 0)
     {
         return "WscContext;Max-Age=0";
     }
     return ContextProtocol.HttpCookieToolbox.EncodeContextAsHttpSetCookieHeader(contextMessageProperty, this.Uri);
 }
        private ContextMessageProperty OnReceiveSoapContextHeader(Message message)
        {
            ContextMessageProperty contextFromHeaderIfExists = ContextMessageHeader.GetContextFromHeaderIfExists(message);

            if ((contextFromHeaderIfExists != null) && DiagnosticUtility.ShouldTraceVerbose)
            {
                TraceUtility.TraceEvent(TraceEventType.Verbose, 0xf0006, System.ServiceModel.SR.GetString("TraceCodeContextProtocolContextRetrievedFromMessage"), this);
            }
            return(contextFromHeaderIfExists);
        }
示例#12
0
        public static string GetContextCorrelationData(Message message)
        {
            ContextMessageProperty contextMessageProperty = null;
            string str = null;

            if (ContextMessageProperty.TryGet(message, out contextMessageProperty))
            {
                contextMessageProperty.Context.TryGetValue("instanceId", out str);
            }
            return(str ?? string.Empty);
        }
示例#13
0
        public static string GetContextCorrelationData(OperationContext operationContext)
        {
            ContextMessageProperty contextMessageProperty = null;
            string str = null;

            if (ContextMessageProperty.TryGet(operationContext.OutgoingMessageProperties, out contextMessageProperty))
            {
                contextMessageProperty.Context.TryGetValue("instanceId", out str);
            }
            return(str ?? string.Empty);
        }
示例#14
0
 string GetCookieHeaderFromContext(ContextMessageProperty contextMessageProperty)
 {
     if (contextMessageProperty.Context.Count == 0)
     {
         return(HttpCookieToolbox.RemoveContextHttpCookieHeader);
     }
     else
     {
         return(HttpCookieToolbox.EncodeContextAsHttpSetCookieHeader(contextMessageProperty, this.Uri));
     }
 }
        public override void OnOutgoingMessage(Message message, System.ServiceModel.Channels.RequestContext requestContext)
        {
            CallbackContextMessageProperty property2;

            if (message == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
            }
            ContextMessageProperty contextMessageProperty = null;

            if (ContextMessageProperty.TryGet(message, out contextMessageProperty) && this.contextManagementEnabled)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("InvalidMessageContext")));
            }
            if (base.ContextExchangeMechanism == ContextExchangeMechanism.ContextSoapHeader)
            {
                if (this.contextManagementEnabled)
                {
                    contextMessageProperty = this.GetCurrentContext();
                }
                if (contextMessageProperty != null)
                {
                    base.OnSendSoapContextHeader(message, contextMessageProperty);
                }
            }
            else if (base.ContextExchangeMechanism == ContextExchangeMechanism.HttpCookie)
            {
                if (this.contextManagementEnabled)
                {
                    this.OnSendHttpCookies(message, null);
                }
                else
                {
                    this.OnSendHttpCookies(message, contextMessageProperty);
                }
            }
            if (CallbackContextMessageProperty.TryGet(message, out property2))
            {
                EndpointAddress callbackAddress = property2.CallbackAddress;
                if ((callbackAddress == null) && (this.callbackAddress != null))
                {
                    callbackAddress = property2.CreateCallbackAddress(this.callbackAddress);
                }
                if (callbackAddress != null)
                {
                    if (base.ContextExchangeMechanism != ContextExchangeMechanism.ContextSoapHeader)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("CallbackContextOnlySupportedInSoap")));
                    }
                    message.Headers.Add(new CallbackContextMessageHeader(callbackAddress, message.Version.Addressing));
                }
            }
        }
        public static string GetContextCorrelationData(OperationContext operationContext)
        {
            ContextMessageProperty contextProperties = null;
            string instanceId = null;

            if (ContextMessageProperty.TryGet(operationContext.OutgoingMessageProperties, out contextProperties))
            {
                contextProperties.Context.TryGetValue(ContextMessageProperty.InstanceIdKey, out instanceId);
            }

            return(instanceId ?? string.Empty);
        }
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            try
            {
                if (reply != null)
                {
                    ContextMessageProperty context = null;

                    if (sessionMode == SessionMode.NotAllowed || reply.Properties.ContainsKey(suppressContextOnReply))
                    {
                        if (ContextMessageProperty.TryGet(reply, out context))
                        {
                            context.Context.Clear();
                        }
                    }
                    else
                    {
                        string newInstanceId = correlationState as string;

                        if (newInstanceId != null)
                        {

                            if (!ContextMessageProperty.TryGet(reply, out context))
                            {
                                context = new ContextMessageProperty();
                                context.Context[WellKnownContextProperties.InstanceId] = newInstanceId;
                                context.AddOrReplaceInMessage(reply);
                            }
                            else
                            {
                                context.Context[WellKnownContextProperties.InstanceId] = newInstanceId;
                            }
                        }
                    }
                }
            }
            finally
            {
                DurableInstance durableInstance = OperationContext.Current.InstanceContext.Extensions.Find<DurableInstance>();

                if (durableInstance == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new InvalidOperationException(
                        SR2.GetString(
                        SR2.RequiredInstanceContextExtensionNotFound,
                        typeof(DurableInstance).Name)));
                }
                //Decrement InstanceActivity Count
                durableInstance.DecrementActivityCount();
            }
        }
 public ClientContextProtocol(ContextExchangeMechanism contextExchangeMechanism, System.Uri uri, IChannel owner, System.Uri callbackAddress, bool contextManagementEnabled) : base(contextExchangeMechanism)
 {
     if (contextExchangeMechanism == ContextExchangeMechanism.HttpCookie)
     {
         this.cookieContainer = new CookieContainer();
     }
     this.context = ContextMessageProperty.Empty;
     this.contextManagementEnabled = contextManagementEnabled;
     this.owner           = owner;
     this.thisLock        = new object();
     this.uri             = uri;
     this.callbackAddress = callbackAddress;
 }
 public ClientContextProtocol(ContextExchangeMechanism contextExchangeMechanism, System.Uri uri, IChannel owner, System.Uri callbackAddress, bool contextManagementEnabled) : base(contextExchangeMechanism)
 {
     if (contextExchangeMechanism == ContextExchangeMechanism.HttpCookie)
     {
         this.cookieContainer = new CookieContainer();
     }
     this.context = ContextMessageProperty.Empty;
     this.contextManagementEnabled = contextManagementEnabled;
     this.owner = owner;
     this.thisLock = new object();
     this.uri = uri;
     this.callbackAddress = callbackAddress;
 }
示例#20
0
        ContextMessageProperty OnReceiveSoapContextHeader(Message message)
        {
            ContextMessageProperty messageProperty = ContextMessageHeader.GetContextFromHeaderIfExists(message);

            if (messageProperty != null)
            {
                if (DiagnosticUtility.ShouldTraceVerbose)
                {
                    TraceUtility.TraceEvent(System.Diagnostics.TraceEventType.Verbose,
                                            TraceCode.ContextProtocolContextRetrievedFromMessage, SR.GetString(SR.TraceCodeContextProtocolContextRetrievedFromMessage),
                                            this);
                }
            }
            return(messageProperty);
        }
示例#21
0
        internal static ContextMessageProperty ParseContextHeader(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            ContextMessageProperty result = new ContextMessageProperty();

            try
            {
                if (!reader.IsEmptyElement)
                {
                    reader.ReadStartElement(ContextHeaderName, ContextHeaderNamespace);

                    while (reader.MoveToContent() == XmlNodeType.Element)
                    {
                        if (reader.LocalName != ContextPropertyElement || reader.NamespaceURI != ContextHeaderNamespace)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                      new ProtocolException(SR.GetString(SR.SchemaViolationInsideContextHeader)));
                        }

                        string propertyName = reader.GetAttribute(ContextPropertyNameAttribute);

                        if (string.IsNullOrEmpty(propertyName) || !ContextDictionary.TryValidateKeyValueSpace(propertyName))
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                      new ProtocolException(SR.GetString(SR.InvalidCookieContent, propertyName)));
                        }
                        result.Context[propertyName] = reader.ReadElementString();
                    }

                    if (reader.NodeType != XmlNodeType.EndElement)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.GetString(SR.SchemaViolationInsideContextHeader)));
                    }
                }
            }
            catch (XmlException e)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new ProtocolException(SR.GetString(SR.XmlFormatViolationInContextHeader), e));
            }

            return(result);
        }
示例#22
0
            public static bool TryCreateFromHttpCookieHeader(string httpCookieHeader, out ContextMessageProperty context)
            {
                if (httpCookieHeader == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("httpCookieHeader");
                }

                context = null;

                foreach (string token in httpCookieHeader.Split(';'))
                {
                    string trimmedToken = token.Trim();
                    if (trimmedToken.StartsWith(HttpCookieToolbox.ContextHttpCookieName, StringComparison.Ordinal))
                    {
                        int equalsSignIndex = trimmedToken.IndexOf('=');
                        if (equalsSignIndex < 0)
                        {
                            context = new ContextMessageProperty();
                            break;
                        }
                        if (equalsSignIndex < (trimmedToken.Length - 1))
                        {
                            string value = trimmedToken.Substring(equalsSignIndex + 1).Trim();

                            if (value.Length > 1 && (value[0] == '"') && (value[value.Length - 1] == '"'))
                            {
                                value = value.Substring(1, value.Length - 2);
                            }
                            try
                            {
                                context = ContextMessageHeader.ParseContextHeader(
                                    XmlReader.Create(new MemoryStream(Convert.FromBase64String(value))));
                                break;
                            }
                            catch (SerializationException e)
                            {
                                DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
                            }
                            catch (ProtocolException pe)
                            {
                                DiagnosticUtility.TraceHandledException(pe, TraceEventType.Warning);
                            }
                        }
                    }
                }

                return(context != null);
            }
        public static ContextMessageProperty GetContextFromHeaderIfExists(Message message)
        {
            if (message == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
            }
            int headerIndex = message.Headers.FindHeader("Context", "http://schemas.microsoft.com/ws/2006/05/context");

            if (headerIndex >= 0)
            {
                MessageHeaders         headers  = message.Headers;
                ContextMessageProperty property = ParseContextHeader(headers.GetReaderAtHeader(headerIndex));
                headers.AddUnderstood(headerIndex);
                return(property);
            }
            return(null);
        }
        public void SetContext(IDictionary <string, string> context)
        {
            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }
            ContextMessageProperty newContext = new ContextMessageProperty(context);

            this.EnsureInvariants(false, newContext);
            if (base.ContextExchangeMechanism == ContextExchangeMechanism.HttpCookie)
            {
                lock (this.cookieContainer)
                {
                    this.cookieContainer.SetCookies(this.Uri, this.GetCookieHeaderFromContext(newContext));
                }
            }
        }
 public static bool TryGet(MessageProperties properties, out ContextMessageProperty contextMessageProperty)
 {
     if (properties == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("properties");
     }
     object obj2 = null;
     if (properties.TryGetValue("ContextMessageProperty", out obj2))
     {
         contextMessageProperty = obj2 as ContextMessageProperty;
     }
     else
     {
         contextMessageProperty = null;
     }
     return (contextMessageProperty != null);
 }
        void OnSendHttpCookies(Message message, ContextMessageProperty context, Uri requestUri)
        {
            object tmpProperty;
            HttpResponseMessageProperty property = null;

            if (message.Properties.TryGetValue(HttpResponseMessageProperty.Name, out tmpProperty))
            {
                property = tmpProperty as HttpResponseMessageProperty;
            }
            if (property == null)
            {
                property = new HttpResponseMessageProperty();
                message.Properties.Add(HttpResponseMessageProperty.Name, property);
            }
            string setCookieHeader = HttpCookieToolbox.EncodeContextAsHttpSetCookieHeader(context, requestUri);

            property.Headers.Add(HttpResponseHeader.SetCookie, setCookieHeader);
        }
示例#27
0
        public static bool TryGet(MessageProperties properties, out ContextMessageProperty contextMessageProperty)
        {
            if (properties == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("properties");
            }
            object obj2 = null;

            if (properties.TryGetValue("ContextMessageProperty", out obj2))
            {
                contextMessageProperty = obj2 as ContextMessageProperty;
            }
            else
            {
                contextMessageProperty = null;
            }
            return(contextMessageProperty != null);
        }
示例#28
0
        void OnSendHttpCookies(Message message, ContextMessageProperty context)
        {
            string cookieHeader = null;

            if (this.contextManagementEnabled || context == null)
            {
                Fx.Assert(context == null, "Context should be null");

                lock (this.cookieContainer)
                {
                    cookieHeader = this.cookieContainer.GetCookieHeader(this.Uri);
                }
            }
            else
            {
                if (context != null) //User provided context is not null.
                {
                    string contextCookieHeader = this.GetCookieHeaderFromContext(context);

                    lock (this.cookieContainer)
                    {
                        this.cookieContainer.SetCookies(this.Uri, contextCookieHeader);
                        cookieHeader = this.cookieContainer.GetCookieHeader(this.Uri);
                        this.cookieContainer.SetCookies(this.Uri, HttpCookieToolbox.RemoveContextHttpCookieHeader);
                    }
                }
            }

            if (!string.IsNullOrEmpty(cookieHeader))
            {
                object tmpProperty;
                HttpRequestMessageProperty property = null;
                if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out tmpProperty))
                {
                    property = tmpProperty as HttpRequestMessageProperty;
                }
                if (property == null)
                {
                    property = new HttpRequestMessageProperty();
                    message.Properties.Add(HttpRequestMessageProperty.Name, property);
                }
                property.Headers.Add(HttpRequestHeader.Cookie, cookieHeader);
            }
        }
        public Microsoft.ResourceManagement.WebServices.Client.ContextualSecurityToken GetContextTokenFromResponse(ContextMessageProperty context)
        {
            Microsoft.ResourceManagement.WebServices.Client.ContextualSecurityToken returnToken = null;
            if (RequestedSecurityToken != null)
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(new XmlNodeReader(RequestedSecurityToken));
                XmlNamespaceManager nsManager = new XmlNamespaceManager(xmlDoc.NameTable);
                nsManager.AddNamespace("saml", "urn:oasis:names:tc:SAML:1.0:assertion");

                DateTime effectiveTime = DateTime.Parse(
                    RequestedSecurityToken.SelectSingleNode(
                        "saml:Conditions/@NotBefore",
                        nsManager
                        ).Value);
                DateTime expirationTime = DateTime.Parse(
                    RequestedSecurityToken.SelectSingleNode(
                        "saml:Conditions/@NotOnOrAfter",
                        nsManager
                        ).Value);
                WSSecurityTokenSerializer serializer = new WSSecurityTokenSerializer();
                SecurityToken requestedProofToken =
                    serializer.ReadToken(
                        new XmlNodeReader(this.RequestedProofToken),
                        new SecurityContextSecurityTokenResolver(Int32.MaxValue, false));
                SecurityKeyIdentifierClause requestedUnattachedReference =
                    serializer.ReadKeyIdentifierClause(new XmlNodeReader(RequestedUnattachedReference));
                SecurityKeyIdentifierClause requestedAttachedReference =
                    serializer.ReadKeyIdentifierClause(new XmlNodeReader(RequestedAttachedReference));

                returnToken = new ContextualSecurityToken(
                        new GenericXmlSecurityToken(
                                RequestedSecurityToken,
                                requestedProofToken,
                                effectiveTime,
                                expirationTime,
                                requestedUnattachedReference,
                                requestedAttachedReference,
                                new ReadOnlyCollection<IAuthorizationPolicy>(new List<IAuthorizationPolicy>())
                            ), context);

            }
            return returnToken;
        }
 public static string EncodeContextAsHttpSetCookieHeader(ContextMessageProperty context, Uri uri)
 {
     if (uri == null)
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("uri");
     }
     if (context == null)
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
     }
     MemoryStream output = new MemoryStream();
     XmlWriterSettings settings = new XmlWriterSettings {
         OmitXmlDeclaration = true
     };
     XmlWriter writer = XmlWriter.Create(output, settings);
     new ContextMessageHeader(context.Context).WriteHeader(writer, MessageVersion.Default);
     writer.Flush();
     return string.Format(CultureInfo.InvariantCulture, "{0}=\"{1}\";Path={2}", new object[] { "WscContext", Convert.ToBase64String(output.GetBuffer(), 0, (int) output.Length), uri.AbsolutePath });
 }
 public static bool TryCreateFromHttpCookieHeader(string httpCookieHeader, out ContextMessageProperty context)
 {
     if (httpCookieHeader == null)
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("httpCookieHeader");
     }
     context = null;
     foreach (string str in httpCookieHeader.Split(new char[] { ';' }))
     {
         string str2 = str.Trim();
         if (str2.StartsWith("WscContext", StringComparison.Ordinal))
         {
             int index = str2.IndexOf('=');
             if (index < 0)
             {
                 context = new ContextMessageProperty();
                 break;
             }
             if (index < (str2.Length - 1))
             {
                 string s = str2.Substring(index + 1).Trim();
                 if (((s.Length > 1) && (s[0] == '"')) && (s[s.Length - 1] == '"'))
                 {
                     s = s.Substring(1, s.Length - 2);
                 }
                 try
                 {
                     context = ContextMessageHeader.ParseContextHeader(XmlReader.Create(new MemoryStream(Convert.FromBase64String(s))));
                     break;
                 }
                 catch (SerializationException exception)
                 {
                     System.ServiceModel.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Warning);
                 }
                 catch (ProtocolException exception2)
                 {
                     System.ServiceModel.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Warning);
                 }
             }
         }
     }
     return (context != null);
 }
 protected void OnSendSoapContextHeader(Message message, ContextMessageProperty context)
 {
     if (message == null)
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
     }
     if (context == null)
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
     }
     if (context.Context.Count > 0)
     {
         message.Headers.Add(new ContextMessageHeader(context.Context));
     }
     if (System.ServiceModel.DiagnosticUtility.ShouldTraceVerbose)
     {
         TraceUtility.TraceEvent(TraceEventType.Verbose, 0xf0005, System.ServiceModel.SR.GetString("TraceCodeContextProtocolContextAddedToMessage"), this);
     }
 }
 protected void OnSendSoapContextHeader(Message message, ContextMessageProperty context)
 {
     if (message == null)
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
     }
     if (context == null)
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
     }
     if (context.Context.Count > 0)
     {
         message.Headers.Add(new ContextMessageHeader(context.Context));
     }
     if (System.ServiceModel.DiagnosticUtility.ShouldTraceVerbose)
     {
         TraceUtility.TraceEvent(TraceEventType.Verbose, 0xf0005, System.ServiceModel.SR.GetString("TraceCodeContextProtocolContextAddedToMessage"), this);
     }
 }
 public static bool TryCreateFromHttpCookieHeader(string httpCookieHeader, out ContextMessageProperty context)
 {
     if (httpCookieHeader == null)
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("httpCookieHeader");
     }
     context = null;
     foreach (string str in httpCookieHeader.Split(new char[] { ';' }))
     {
         string str2 = str.Trim();
         if (str2.StartsWith("WscContext", StringComparison.Ordinal))
         {
             int index = str2.IndexOf('=');
             if (index < 0)
             {
                 context = new ContextMessageProperty();
                 break;
             }
             if (index < (str2.Length - 1))
             {
                 string s = str2.Substring(index + 1).Trim();
                 if (((s.Length > 1) && (s[0] == '"')) && (s[s.Length - 1] == '"'))
                 {
                     s = s.Substring(1, s.Length - 2);
                 }
                 try
                 {
                     context = ContextMessageHeader.ParseContextHeader(XmlReader.Create(new MemoryStream(Convert.FromBase64String(s))));
                     break;
                 }
                 catch (SerializationException exception)
                 {
                     System.ServiceModel.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Warning);
                 }
                 catch (ProtocolException exception2)
                 {
                     System.ServiceModel.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Warning);
                 }
             }
         }
     }
     return(context != null);
 }
示例#35
0
        //Called to update local context
        //1) From SetContext(to update client provided context)
        //2) From OnReceive*(to update server issued)
        void EnsureInvariants(bool isServerIssued, ContextMessageProperty newContext)
        {
            //Cannot SetContext when ContextManagement not enabled.
            if (!this.contextManagementEnabled)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new InvalidOperationException(
                              SR.GetString(SR.ContextManagementNotEnabled)
                              ));
            }

            //Cannot reset context after initialized in server case.
            if ((isServerIssued && !this.contextInitialized) ||
                (this.owner.State == CommunicationState.Created))
            {
                lock (this.thisLock)
                {
                    if ((isServerIssued && !this.contextInitialized) ||
                        (this.owner.State == CommunicationState.Created))
                    {
                        this.context            = newContext;
                        this.contextInitialized = true;
                        return;
                    }
                }
            }

            if (isServerIssued)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new ProtocolException(
                              SR.GetString(SR.InvalidContextReceived)
                              ));
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new InvalidOperationException(
                              SR.GetString(SR.CachedContextIsImmutable)
                              ));
            }
        }
            public static string EncodeContextAsHttpSetCookieHeader(ContextMessageProperty context, Uri uri)
            {
                if (uri == null)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("uri");
                }
                if (context == null)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
                }
                MemoryStream      output   = new MemoryStream();
                XmlWriterSettings settings = new XmlWriterSettings {
                    OmitXmlDeclaration = true
                };
                XmlWriter writer = XmlWriter.Create(output, settings);

                new ContextMessageHeader(context.Context).WriteHeader(writer, MessageVersion.Default);
                writer.Flush();
                return(string.Format(CultureInfo.InvariantCulture, "{0}=\"{1}\";Path={2}", new object[] { "WscContext", Convert.ToBase64String(output.GetBuffer(), 0, (int)output.Length), uri.AbsolutePath }));
            }
示例#37
0
        public static ContextMessageProperty GetContextFromHeaderIfExists(Message message)
        {
            if (message == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
            }

            int i = message.Headers.FindHeader(ContextHeaderName, ContextHeaderNamespace);

            if (i >= 0)
            {
                MessageHeaders         headers = message.Headers;
                ContextMessageProperty context = ParseContextHeader(headers.GetReaderAtHeader(i));
                headers.AddUnderstood(i);
                return(context);
            }
            else
            {
                return(null);
            }
        }
        public override void OnOutgoingMessage(Message message, RequestContext requestContext)
        {
            if (message == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
            }

            ContextMessageProperty messageContext;

            if (ContextMessageProperty.TryGet(message, out messageContext))
            {
                if (this.ContextExchangeMechanism == ContextExchangeMechanism.HttpCookie)
                {
                    Fx.Assert(requestContext != null, "DuplexChannel shape cannot have ContextExchangeMechanism = HttpCookie");
                    Uri requestUri = null;

                    if (requestContext.RequestMessage.Properties != null)
                    {
                        requestUri = requestContext.RequestMessage.Properties.Via;
                    }
                    if (requestUri == null)
                    {
                        requestUri = requestContext.RequestMessage.Headers.To;
                    }
                    this.OnSendHttpCookies(message, messageContext, requestUri);
                }
                else
                {
                    this.OnSendSoapContextHeader(message, messageContext);
                }
            }
            // verify that the callback context was not attached to an outgoing message
            CallbackContextMessageProperty dummy;

            if (CallbackContextMessageProperty.TryGet(message, out dummy))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.CallbackContextNotExpectedOnOutgoingMessageAtServer, message.Headers.Action)));
            }
        }
        internal static ContextMessageProperty ParseContextHeader(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }
            ContextMessageProperty property = new ContextMessageProperty();

            try
            {
                if (reader.IsEmptyElement)
                {
                    return(property);
                }
                reader.ReadStartElement("Context", "http://schemas.microsoft.com/ws/2006/05/context");
                while (reader.MoveToContent() == XmlNodeType.Element)
                {
                    if ((reader.LocalName != "Property") || (reader.NamespaceURI != "http://schemas.microsoft.com/ws/2006/05/context"))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("SchemaViolationInsideContextHeader")));
                    }
                    string attribute = reader.GetAttribute("name");
                    if (string.IsNullOrEmpty(attribute) || !ContextDictionary.TryValidateKeyValueSpace(attribute))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("InvalidCookieContent", new object[] { attribute })));
                    }
                    property.Context[attribute] = reader.ReadElementString();
                }
                if (reader.NodeType != XmlNodeType.EndElement)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("SchemaViolationInsideContextHeader")));
                }
            }
            catch (XmlException exception)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("XmlFormatViolationInContextHeader"), exception));
            }
            return(property);
        }
        private void OnSendHttpCookies(Message message, ContextMessageProperty context)
        {
            string cookieHeader = null;

            if (this.contextManagementEnabled || (context == null))
            {
                lock (this.cookieContainer)
                {
                    cookieHeader = this.cookieContainer.GetCookieHeader(this.Uri);
                    goto Label_00A2;
                }
            }
            if (context != null)
            {
                string cookieHeaderFromContext = this.GetCookieHeaderFromContext(context);
                lock (this.cookieContainer)
                {
                    this.cookieContainer.SetCookies(this.Uri, cookieHeaderFromContext);
                    cookieHeader = this.cookieContainer.GetCookieHeader(this.Uri);
                    this.cookieContainer.SetCookies(this.Uri, "WscContext;Max-Age=0");
                }
            }
Label_00A2:
            if (!string.IsNullOrEmpty(cookieHeader))
            {
                object obj2;
                HttpRequestMessageProperty property = null;
                if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out obj2))
                {
                    property = obj2 as HttpRequestMessageProperty;
                }
                if (property == null)
                {
                    property = new HttpRequestMessageProperty();
                    message.Properties.Add(HttpRequestMessageProperty.Name, property);
                }
                property.Headers.Add(HttpRequestHeader.Cookie, cookieHeader);
            }
        }
 private void EnsureInvariants(bool isServerIssued, ContextMessageProperty newContext)
 {
     if (!this.contextManagementEnabled)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("ContextManagementNotEnabled")));
     }
     if ((isServerIssued && !this.contextInitialized) || (this.owner.State == CommunicationState.Created))
     {
         lock (this.thisLock)
         {
             if ((isServerIssued && !this.contextInitialized) || (this.owner.State == CommunicationState.Created))
             {
                 this.context = newContext;
                 this.contextInitialized = true;
                 return;
             }
         }
     }
     if (isServerIssued)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("InvalidContextReceived")));
     }
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("CachedContextIsImmutable")));
 }
 private void OnSendHttpCookies(Message message, ContextMessageProperty context)
 {
     string cookieHeader = null;
     if (this.contextManagementEnabled || (context == null))
     {
         lock (this.cookieContainer)
         {
             cookieHeader = this.cookieContainer.GetCookieHeader(this.Uri);
             goto Label_00A2;
         }
     }
     if (context != null)
     {
         string cookieHeaderFromContext = this.GetCookieHeaderFromContext(context);
         lock (this.cookieContainer)
         {
             this.cookieContainer.SetCookies(this.Uri, cookieHeaderFromContext);
             cookieHeader = this.cookieContainer.GetCookieHeader(this.Uri);
             this.cookieContainer.SetCookies(this.Uri, "WscContext;Max-Age=0");
         }
     }
 Label_00A2:
     if (!string.IsNullOrEmpty(cookieHeader))
     {
         object obj2;
         HttpRequestMessageProperty property = null;
         if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out obj2))
         {
             property = obj2 as HttpRequestMessageProperty;
         }
         if (property == null)
         {
             property = new HttpRequestMessageProperty();
             message.Properties.Add(HttpRequestMessageProperty.Name, property);
         }
         property.Headers.Add(HttpRequestHeader.Cookie, cookieHeader);
     }
 }
            static bool HandleEndGetInstance(IAsyncResult result)
            {
                ControlOperationAsyncResult thisPtr = (ControlOperationAsyncResult)result.AsyncState;

                bool shouldAbandon = true;
                try
                {
                    try
                    {
                        thisPtr.workflowServiceInstance = thisPtr.invoker.instanceManager.EndGetInstance(result);
                        shouldAbandon = false;
                    }
                    catch (InstanceLockedException exception)
                    {
                        RedirectionException redirectionException;
                        if (thisPtr.TryCreateRedirectionException(exception, out redirectionException))
                        {
                            throw FxTrace.Exception.AsError(redirectionException);
                        }
                        throw FxTrace.Exception.AsError(CreateFaultException(exception));
                    }
                    catch (OperationCanceledException exception)
                    {
                        thisPtr.BufferReceiveHelper(ref shouldAbandon, true);
                        throw FxTrace.Exception.AsError(new RetryException(null, exception));
                    }
                    catch (InstancePersistenceException exception)
                    {
                        thisPtr.BufferReceiveHelper(ref shouldAbandon, false);

                        if (exception is InstanceKeyNotReadyException)
                        {
                            thisPtr.invoker.host.RaiseUnknownMessageReceived(thisPtr.operationContext.IncomingMessage);
                        }

                        thisPtr.invoker.host.FaultServiceHostIfNecessary(exception);

                        throw FxTrace.Exception.AsError(CreateFaultException(exception));
                    }
                    catch (InstanceUpdateException)
                    {
                        throw FxTrace.Exception.AsError(new FaultException(OperationExecutionFault.CreateUpdateFailedFault(
                            SR.WorkflowInstanceUpdateFailed(thisPtr.instanceId, thisPtr.updatedIdentity.Identity))));
                    }
                }
                catch (Exception exception)
                {
                    if (Fx.IsFatal(exception))
                    {
                        throw;
                    }
                    if (!shouldAbandon || !thisPtr.ShouldAbandonReceiveContext())
                    {
                        throw;
                    }
                    return thisPtr.AbandonReceiveContext(exception);
                }

                // When creating a new instance for a normal, keyless app message, create a key for use by context exchange.
                if (!thisPtr.instanceKey.IsValid && thisPtr.instanceId == Guid.Empty)
                {
                    ContextMessageProperty outgoingContextMessageProperty = null;

                    if (!ContextMessageProperty.TryGet(thisPtr.operationContext.OutgoingMessageProperties, out outgoingContextMessageProperty))
                    {
                        outgoingContextMessageProperty = new ContextMessageProperty();
                        outgoingContextMessageProperty.Context.Add(ContextMessageProperty.InstanceIdKey, Guid.NewGuid().ToString());
                        outgoingContextMessageProperty.AddOrReplaceInMessageProperties(thisPtr.operationContext.OutgoingMessageProperties);
                    }
                    else
                    {
                        outgoingContextMessageProperty.Context[ContextMessageProperty.InstanceIdKey] = Guid.NewGuid().ToString();
                    }
                }
                return thisPtr.PerformOperation();
            }
 private static bool HandleEndGetInstance(IAsyncResult result)
 {
     ControlOperationInvoker.ControlOperationAsyncResult asyncState = (ControlOperationInvoker.ControlOperationAsyncResult) result.AsyncState;
     bool shouldAbandon = true;
     try
     {
         try
         {
             asyncState.workflowServiceInstance = asyncState.invoker.instanceManager.EndGetInstance(result);
             shouldAbandon = false;
         }
         catch (InstanceLockedException exception)
         {
             RedirectionException exception2;
             if (asyncState.TryCreateRedirectionException(exception, out exception2))
             {
                 throw System.ServiceModel.Activities.FxTrace.Exception.AsError(exception2);
             }
             throw System.ServiceModel.Activities.FxTrace.Exception.AsError(CreateFaultException(exception));
         }
         catch (OperationCanceledException exception3)
         {
             asyncState.BufferReceiveHelper(ref shouldAbandon, true);
             throw System.ServiceModel.Activities.FxTrace.Exception.AsError(new RetryException(null, exception3));
         }
         catch (InstancePersistenceException exception4)
         {
             asyncState.BufferReceiveHelper(ref shouldAbandon, false);
             if (exception4 is InstanceKeyNotReadyException)
             {
                 asyncState.invoker.host.RaiseUnknownMessageReceived(asyncState.operationContext.IncomingMessage);
             }
             asyncState.invoker.host.FaultServiceHostIfNecessary(exception4);
             throw System.ServiceModel.Activities.FxTrace.Exception.AsError(CreateFaultException(exception4));
         }
     }
     catch (Exception exception5)
     {
         if (Fx.IsFatal(exception5))
         {
             throw;
         }
         if (!shouldAbandon || !asyncState.ShouldAbandonReceiveContext())
         {
             throw;
         }
         return asyncState.AbandonReceiveContext(exception5);
     }
     if (!asyncState.instanceKey.IsValid && (asyncState.instanceId == Guid.Empty))
     {
         ContextMessageProperty contextMessageProperty = null;
         if (!ContextMessageProperty.TryGet(asyncState.operationContext.OutgoingMessageProperties, out contextMessageProperty))
         {
             contextMessageProperty = new ContextMessageProperty();
             contextMessageProperty.Context.Add("instanceId", Guid.NewGuid().ToString());
             contextMessageProperty.AddOrReplaceInMessageProperties(asyncState.operationContext.OutgoingMessageProperties);
         }
         else
         {
             contextMessageProperty.Context["instanceId"] = Guid.NewGuid().ToString();
         }
     }
     return asyncState.PerformOperation();
 }
示例#45
0
        public static void OTPReset(string domain, string username, ContextualSecurityToken authNSecurityToken, ContextMessageProperty contextMessageProperty)
        {
            // Create Anonymouse RmPerson and set ObjectID to Domain\User
            // The ObjectID attribute will become ResourceReferenceProperty in the message header
            RmPerson user = new RmPerson();
            RmReference domainAndUsernameReference = new RmReference();
            domainAndUsernameReference.DomainAndUserNameValue = domain + '\\' + username;
            user.ObjectID = domainAndUsernameReference;
            PutResponse putResponse;
            putResponse = new PutResponse();
            string STSEndpoint = String.Empty;
            bool putSuccess = false; //This should always stay false with these calls unless no password reset workflow or qa authn workflow is attached.

            var alternateClient = new AlternateClient();
            var mexClient = new MexClient();
            XmlSchemaSet metadata = mexClient.Get();
            var requestFactory = new RmRequestFactory(metadata);

            // Set ResetPassword to true
            // Need a transaction to watch changes to the user
            using (RmResourceChanges transaction = new RmResourceChanges(user))
            {
                transaction.BeginChanges();

                user.ResetPassword = "******";

                try
                {
                    if (transaction.RmObject.ObjectID.Value.Split('\\').Length != 2)
                    {
                        throw new ArgumentException("User Identity must be specified by netbios domain in this format: Domain name\\user name.");
                    }

                    PutRequest alternateEPrequest = requestFactory.CreatePutRequest(transaction);

                    try
                    {
                        alternateClient.Put(alternateEPrequest, out putResponse, authNSecurityToken, contextMessageProperty);
                        putSuccess = true;
                    }
                    catch (System.ServiceModel.FaultException<Microsoft.ResourceManagement.Client.Faults.AuthenticationRequiredFault> authNFault)
                    {

                        Microsoft.ResourceManagement.WebServices.WSResourceManagement.AuthenticationRequiredFault msAuthNFault =
                            new Microsoft.ResourceManagement.WebServices.WSResourceManagement.AuthenticationRequiredFault(authNFault.Detail.SecurityTokenServiceAddress,
                                                                                             authNFault.Detail.UserRegistered.GetValueOrDefault(),
                                                                                             authNFault.Detail.UserLockedOut.GetValueOrDefault());

                        ContextMessageProperty responseContext;

                        if (ContextMessageProperty.TryGet(putResponse.Message, out responseContext) == false)
                        {
                            throw new InvalidOperationException("Could not retrieve security context message property even though we received an AuthN Fault. Something is fundamentally broken. Ensure assembly versions are correct and upgrades did not change protocol.");
                        }

                        throw new AuthenticationRequiredException(authNFault.Reason.ToString(),
                                                                 msAuthNFault,
                                                                 responseContext);
                    }
                }
                finally
                {
                    if (putSuccess == true)
                    {
                        transaction.AcceptChanges();
                    }
                    else
                    {
                        transaction.DiscardChanges();
                    }
                }
            }
        }
            public static bool TryCreateFromHttpCookieHeader(string httpCookieHeader, out ContextMessageProperty context)
            {
                if (httpCookieHeader == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("httpCookieHeader");
                }

                context = null;

                foreach (string token in httpCookieHeader.Split(';'))
                {
                    string trimmedToken = token.Trim();
                    if (trimmedToken.StartsWith(HttpCookieToolbox.ContextHttpCookieName, StringComparison.Ordinal))
                    {
                        int equalsSignIndex = trimmedToken.IndexOf('=');
                        if (equalsSignIndex < 0)
                        {
                            context = new ContextMessageProperty();
                            break;
                        }
                        if (equalsSignIndex < (trimmedToken.Length - 1))
                        {
                            string value = trimmedToken.Substring(equalsSignIndex + 1).Trim();

                            if (value.Length > 1 && (value[0] == '"') && (value[value.Length - 1] == '"'))
                            {
                                value = value.Substring(1, value.Length - 2);
                            }
                            try
                            {
                                context = ContextMessageHeader.ParseContextHeader(
                                    XmlReader.Create(new MemoryStream(Convert.FromBase64String(value))));
                                break;
                            }
                            catch (SerializationException e)
                            {
                                DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
                            }
                            catch (ProtocolException pe)
                            {
                                DiagnosticUtility.TraceHandledException(pe, TraceEventType.Warning);
                            }
                        }
                    }
                }

                return context != null;
            }
示例#47
0
        public bool Put(RmResourceChanges transaction, bool useAlternateEndpoint, out PutResponse response, SecurityToken token, ContextMessageProperty context)
        {
            response = null;
            if (transaction == null) {
                throw new ArgumentNullException("transaction");
            }

            if (!useAlternateEndpoint) {
                PutRequest resourceEPrequest = this.requestFactory.CreatePutRequest(transaction);
                try {

                    this.wsTransferClient.Put(resourceEPrequest, out response);

                }
                    //catch AuthN Fault here so we have the original transaction so we can re-submit later
                catch (System.ServiceModel.FaultException<Microsoft.ResourceManagement.Client.Faults.AuthenticationRequiredFault> authNFault) {
                    String STSEndpoinAddresst = authNFault.Detail.SecurityTokenServiceAddress;
                    ContextMessageProperty responseContext;
                    //TODO: Add AuthNLogicHere. For now, only support QA gates on the Authernate Endpoint
                }

                if (response == null)
                    return false;
                else
                    return true;
            } else {
                //TODO:Verify that the ObjectID is in the form Domain\User.
                PutRequest alternateEPrequest = this.requestFactory.CreatePutRequest(transaction);
                response = null;

                try {
                    this.alternateClient.Put(alternateEPrequest, out response, token, context);
                } catch (System.ServiceModel.FaultException<Microsoft.ResourceManagement.Client.Faults.AuthenticationRequiredFault> authNFault) {
                    String STSEndpointAddress = authNFault.Detail.SecurityTokenServiceAddress;
                    ContextMessageProperty responseContext;

                    if (ContextMessageProperty.TryGet(response.Message, out responseContext)) {
                        ContextualSecurityToken userToken = HandleAuthNFault(STSEndpointAddress, responseContext);
                        Put(transaction, true, out response, userToken, responseContext);
                    } else {
                        throw new Exception("Could not get security context from Put.");
                    }
                }

                if (response == null)
                    return false;
                else
                    return true;
            }
        }
示例#48
0
        private ContextualSecurityToken HandleAuthNFault(String stsEndpointAddress, ContextMessageProperty responseContext)
        {
            ContextualSecurityToken returnToken = null;

            //create new client to talk to the STS
            SecurityTokenServiceClient stsClient = new SecurityTokenServiceClient("ServiceMultipleTokenBinding_SecurityTokenService", stsEndpointAddress);

            Guid contextGuid = new Guid(responseContext.Context["instanceId"]);

            Message RST;  //The Request for Security Token
            Message RSTR;  //The Request for Security Token Response
            ClientSerializer RSTRSerializer = new ClientSerializer(typeof(Client.WsTrust.RequestSecurityTokenResponse));
            Client.WsTrust.RequestSecurityTokenResponse serializedRSTR;
            Dictionary<int, String> answers = new Dictionary<int, string>();

            //Initial RST, RSTR

            RST = stsClient.BuildRequestSecurityTokenMessage(contextGuid);

            RSTR = stsClient.RequestSecurityToken(RST);

            //We will continue asking for RSTR untill we get a Security Token (or get a fault)
            do {
                serializedRSTR = (Client.WsTrust.RequestSecurityTokenResponse)RSTRSerializer.ReadObject(RSTR.GetReaderAtBodyContents());
                if (serializedRSTR != null) {
                    if (serializedRSTR.Authchallenge != null) {
                        if (serializedRSTR.Authchallenge.challenge.workflowAuthChallenge.Name == "QAGate") {
                            answers = questionHandler.Invoke(serializedRSTR.Authchallenge.challenge.workflowAuthChallenge);
                            Client.WsTrust.RequestSecurityTokenResponse RSTRrequest = new Client.WsTrust.RequestSecurityTokenResponse();
                            RSTRrequest.Context = serializedRSTR.Context;
                            RSTRrequest.AuthChallengeResponse = new AuthenticationChallengeResponse(answers);

                            RSTR = stsClient.BuildRequestSecurityTokenResponseMessage(RSTRrequest);
                            RSTR = stsClient.RequestSecurityTokenResponse(RSTR);
                        }
                    } else if (serializedRSTR.RequestedSecurityToken != null) {
                        returnToken = serializedRSTR.GetContextTokenFromResponse(responseContext);
                    } else {
                        throw new Exception("The STS returned a response that is neither an AuthChallenge nor a Security Response.");
                    }
                } else
                    throw new Exception("Received a response from the STS that we do not understand.");

            } while (returnToken == null);

            return returnToken;
        }
 void OnSendHttpCookies(Message message, ContextMessageProperty context, Uri requestUri)
 {
     object tmpProperty;
     HttpResponseMessageProperty property = null;
     if (message.Properties.TryGetValue(HttpResponseMessageProperty.Name, out tmpProperty))
     {
         property = tmpProperty as HttpResponseMessageProperty;
     }
     if (property == null)
     {
         property = new HttpResponseMessageProperty();
         message.Properties.Add(HttpResponseMessageProperty.Name, property);
     }
     string setCookieHeader = HttpCookieToolbox.EncodeContextAsHttpSetCookieHeader(context, requestUri);
     property.Headers.Add(HttpResponseHeader.SetCookie, setCookieHeader);
 }
        internal static ContextMessageProperty ParseContextHeader(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            ContextMessageProperty result = new ContextMessageProperty();
            try
            {
                if (!reader.IsEmptyElement)
                {
                    reader.ReadStartElement(ContextHeaderName, ContextHeaderNamespace);

                    while (reader.MoveToContent() == XmlNodeType.Element)
                    {
                        if (reader.LocalName != ContextPropertyElement || reader.NamespaceURI != ContextHeaderNamespace)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                new ProtocolException(SR.GetString(SR.SchemaViolationInsideContextHeader)));
                        }

                        string propertyName = reader.GetAttribute(ContextPropertyNameAttribute);

                        if (string.IsNullOrEmpty(propertyName) || !ContextDictionary.TryValidateKeyValueSpace(propertyName))
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                new ProtocolException(SR.GetString(SR.InvalidCookieContent, propertyName)));
                        }
                        result.Context[propertyName] = reader.ReadElementString();
                    }

                    if (reader.NodeType != XmlNodeType.EndElement)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                            new ProtocolException(SR.GetString(SR.SchemaViolationInsideContextHeader)));
                    }
                }
            }
            catch (XmlException e)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new ProtocolException(SR.GetString(SR.XmlFormatViolationInContextHeader), e));
            }

            return result;
        }
        void OnSendHttpCookies(Message message, ContextMessageProperty context)
        {
            string cookieHeader = null;

            if (this.contextManagementEnabled || context == null)
            {
                Fx.Assert(context == null, "Context should be null");

                lock (this.cookieContainer)
                {
                    cookieHeader = this.cookieContainer.GetCookieHeader(this.Uri);
                }
            }
            else
            {
                if (context != null) //User provided context is not null.
                {
                    string contextCookieHeader = this.GetCookieHeaderFromContext(context);

                    lock (this.cookieContainer)
                    {
                        this.cookieContainer.SetCookies(this.Uri, contextCookieHeader);
                        cookieHeader = this.cookieContainer.GetCookieHeader(this.Uri);
                        this.cookieContainer.SetCookies(this.Uri, HttpCookieToolbox.RemoveContextHttpCookieHeader);
                    }
                }
            }

            if (!string.IsNullOrEmpty(cookieHeader))
            {
                object tmpProperty;
                HttpRequestMessageProperty property = null;
                if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out tmpProperty))
                {
                    property = tmpProperty as HttpRequestMessageProperty;
                }
                if (property == null)
                {
                    property = new HttpRequestMessageProperty();
                    message.Properties.Add(HttpRequestMessageProperty.Name, property);
                }
                property.Headers.Add(HttpRequestHeader.Cookie, cookieHeader);
            }
        }
 string GetCookieHeaderFromContext(ContextMessageProperty contextMessageProperty)
 {
     if (contextMessageProperty.Context.Count == 0)
     {
         return HttpCookieToolbox.RemoveContextHttpCookieHeader;
     }
     else
     {
         return HttpCookieToolbox.EncodeContextAsHttpSetCookieHeader(contextMessageProperty, this.Uri);
     }
 }
        //Called to update local context
        //1) From SetContext(to update client provided context)
        //2) From OnReceive*(to update server issued)
        void EnsureInvariants(bool isServerIssued, ContextMessageProperty newContext)
        {
            //Cannot SetContext when ContextManagement not enabled.
            if (!this.contextManagementEnabled)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(
                    SR.GetString(SR.ContextManagementNotEnabled)
                    ));
            }

            //Cannot reset context after initialized in server case.
            if ((isServerIssued && !this.contextInitialized) ||
                (this.owner.State == CommunicationState.Created))
            {
                lock (this.thisLock)
                {
                    if ((isServerIssued && !this.contextInitialized) ||
                        (this.owner.State == CommunicationState.Created))
                    {
                        this.context = newContext;
                        this.contextInitialized = true;
                        return;
                    }
                }
            }

            if (isServerIssued)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new ProtocolException(
                    SR.GetString(SR.InvalidContextReceived)
                    ));
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(
                    SR.GetString(SR.CachedContextIsImmutable)
                    ));
            }

        }
        public void SetContext(IDictionary<string, string> context)
        {
            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            ContextMessageProperty newContext = new ContextMessageProperty(context);

            EnsureInvariants(false, newContext);

            if (this.ContextExchangeMechanism == ContextExchangeMechanism.HttpCookie)
            {
                lock (this.cookieContainer)
                {
                    this.cookieContainer.SetCookies(this.Uri, GetCookieHeaderFromContext(newContext));
                }
            }
        }
 public static bool TryCreateFromHttpCookieHeader(string httpCookieHeader, out ContextMessageProperty context)
 {
     return ContextProtocol.HttpCookieToolbox.TryCreateFromHttpCookieHeader(httpCookieHeader, out context);
 }