//Called by the service to read incoming context over context bindings
        public static string GetContext(string key)
        {
            try
            {
                if (OperationContext.Current == null)
                {
                    return(null);
                }
                ContextMessageProperty contextProperty = OperationContext.Current.IncomingMessageProperties[ContextMessageProperty.Name] as ContextMessageProperty;

                if (contextProperty.Context.ContainsKey(key) == false)
                {
                    return(null);
                }
                return(contextProperty.Context[key]);
            }
            catch (ArgumentException exception)
            {
                if (exception.Message == "A property with the name 'ContextMessageProperty' is not present.")
                {
                    return(null);
                }
                throw;
            }
        }
Пример #2
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);
        }
        internal static bool RemoveInstanceIdFromMessage(Message message)
        {
            ContextMessageProperty contextProperties = null;

            bool found = ContextMessageProperty.TryGet(message, out contextProperties);

            if (found)
            {
                contextProperties.Context.Remove(ContextManager.InstanceIdKey);
            }
            return(found);
        }
        public static CorrelationContext CreateCorrelationContext(MessageProperties messageProperties)
        {
            ContextMessageProperty property;

            if (ContextMessageProperty.TryGet(messageProperties, out property))
            {
                IDictionary <string, string> context = property.Context;
                return(new CorrelationContext {
                    Context = context
                });
            }
            return(null);
        }
        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();
            }
        }
        internal static Guid GetInstanceIdFromMessage(Message message)
        {
            string instanceId = null;
            ContextMessageProperty contextProperties = null;

            if (ContextMessageProperty.TryGet(message, out contextProperties))
            {
                if (contextProperties.Context.TryGetValue(ContextManager.InstanceIdKey, out instanceId))
                {
                    return(new Guid(instanceId));
                }
            }
            return(Guid.Empty);
        }
        IDictionary <string, string> GetContextProperties()
        {
            Fx.Assert(OperationContext.Current != null, "Called from non service thread");

            ContextMessageProperty incomingContextProperties = null;

            if (OperationContext.Current.IncomingMessageProperties != null &&
                ContextMessageProperty.TryGet(OperationContext.Current.IncomingMessageProperties, out incomingContextProperties))
            {
                return(incomingContextProperties.Context);
            }
            else
            {
                return(SerializableReadOnlyDictionary <string, string> .Empty);
            }
        }
Пример #8
0
        internal static void UpdateLogicalChannelContext(LogicalChannel logicalChannel)
        {
            Fx.Assert(OperationContext.Current != null, "Can be called from valid OperationContextScope");

            WorkflowTrace.Host.TraceEvent(TraceEventType.Verbose, 0,
                                          "ChannelManagerService: updating context associated with logical channel {0}",
                                          logicalChannel.InstanceId);

            ContextMessageProperty contextMessageProperty;
            MessageProperties      properties = OperationContext.Current.IncomingMessageProperties;

            if (properties != null && ContextMessageProperty.TryGet(properties, out contextMessageProperty))
            {
                logicalChannel.Context = contextMessageProperty.Context;
            }
        }
        protected virtual Guid GetInstanceIdFromMessage(Message message)
        {
            if (!this.isPerCall)
            {
                ContextMessageProperty contextProperties = null;
                string instanceId = null;

                if (ContextMessageProperty.TryGet(message, out contextProperties))
                {
                    if (contextProperties.Context.TryGetValue(WellKnownContextProperties.InstanceId, out instanceId))
                    {
                        return(Fx.CreateGuid(instanceId));
                    }
                }
            }
            return(Guid.Empty);
        }
Пример #10
0
        protected override Guid OnGetInstanceId(object[] inputs, OperationContext operationContext)
        {
            Fx.Assert(operationContext.IncomingMessageHeaders.Action == RaiseEventAction, "Message action is not RaiseEvent");
            Guid instanceId = Guid.Empty;
            ContextMessageProperty contextMessageProperty;

            if (ContextMessageProperty.TryGet(operationContext.IncomingMessageProperties, out contextMessageProperty))
            {
                string stringInstanceId = null;
                if (contextMessageProperty.Context.TryGetValue("instanceId", out stringInstanceId))
                {
                    Fx.TryCreateGuid(stringInstanceId, out instanceId);
                }
            }

            return(instanceId);
        }
Пример #11
0
 //Called by the service to read incoming context over context bindings
 public static string GetContext(string key)
 {
     if (OperationContext.Current == null)
     {
         return(null);
     }
     if (OperationContext.Current.IncomingMessageProperties.ContainsKey(ContextMessageProperty.Name))
     {
         ContextMessageProperty contextProperty = OperationContext.Current.IncomingMessageProperties[ContextMessageProperty.Name] as ContextMessageProperty;
         if (contextProperty.Context.ContainsKey(key) == false)
         {
             return(null);
         }
         return(contextProperty.Context[key]);
     }
     else
     {
         return(null);
     }
 }
        void PromoteContextProperties()
        {
            Fx.Assert(OperationContext.Current != null, "Called from non service thread");

            if (outgoingContextProperties != null)
            {
                ContextMessageProperty context;
                if (!ContextMessageProperty.TryGet(OperationContext.Current.OutgoingMessageProperties, out context))
                {
                    new ContextMessageProperty(this.outgoingContextProperties).AddOrReplaceInMessageProperties(OperationContext.Current.OutgoingMessageProperties);
                }
                else
                {
                    foreach (KeyValuePair <string, string> contextElement in this.outgoingContextProperties)
                    {
                        context.Context[contextElement.Key] = contextElement.Value;
                    }
                }
            }
        }
        internal static void SetInstanceIdInMessage(Message message, string instanceId)
        {
            ContextMessageProperty contextProperties = null;

            if (!ContextMessageProperty.TryGet(message, out contextProperties))
            {
                contextProperties = new ContextMessageProperty(ContextManager.CreateContext(ContextManager.InstanceIdKey, instanceId));
                message.Properties.Add(ContextMessageProperty.Name, contextProperties);
            }
            else
            {
                if (!contextProperties.Context.ContainsKey(ContextManager.InstanceIdKey))
                {
                    contextProperties.Context.Add(ContextManager.InstanceIdKey, instanceId);
                }
                else
                {
                    contextProperties.Context[ContextManager.InstanceIdKey] = instanceId;
                }
            }
        }
Пример #14
0
        public void Put(PutRequest request, out PutResponse response, SecurityToken token, ContextMessageProperty context)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            if (request.ModifyRequest == null)
            {
                throw new ArgumentNullException("ModifyRequest");
            }
            if (request.ResourceReferenceProperty == null)
            {
                throw new ArgumentNullException("ResourceReferenceProperty");
            }

            Message putRequest  = null;
            Message putResponse = null;

            lock (request)
            {
                putRequest = Message.CreateMessage(MessageVersion.Default, Constants.WsTransfer.PutAction, request.ModifyRequest, new ClientSerializer(typeof(ModifyRequest)));
                ClientHelper.AddImdaHeaders(request as ImdaRequest, putRequest);
                ClientHelper.AddRmHeaders(request as WsTransfer.TransferRequest, putRequest);
                if (context != null)
                {
                    context.AddOrReplaceInMessage(putRequest);
                }
            }

            if (token == null)
            {
                putResponse = Put(putRequest);
                response    = new PutResponse(putResponse);
            }
            else
            {
                putResponse = Put(putRequest, token);
                response    = new PutResponse(putResponse);
            }
            if (putResponse.IsFault)
            {
                ClientHelper.HandleFault(putResponse);
            }

            // the response has no information if it isn't a fault
            // PutResponse putResponseTyped = putResponse.GetBody<PutResponse>(new ClientSerializer(typeof(PutResponse)));
        }
            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());
            }
Пример #16
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);
                }
            }
        }
        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);
        }
Пример #18
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();
                    }
                }
            }
        }