Примечание.
Для доступа к этой странице требуется авторизация. Вы можете попробовать войти или изменить каталоги.
Для доступа к этой странице требуется авторизация. Вы можете попробовать изменить каталоги.
Критически важные для времени функции можно сорвать, если параметры часов на двух компьютерах отличаются. Чтобы избежать этой возможности, можно установить свойство MaxClockSkew в значение TimeSpan. Это свойство доступно в двух классах:
Это важно
Для безопасной беседы необходимо вносить изменения в MaxClockSkew свойство при загрузке службы или клиента. Для этого необходимо задать свойство, SecurityBindingElement возвращаемое свойством SecureConversationSecurityTokenParameters.BootstrapSecurityBindingElement .
Чтобы изменить свойство для одной из системных привязок, необходимо найти элемент привязки безопасности в коллекции привязок и задать MaxClockSkew для свойства новое значение. Два класса являются производными от SecurityBindingElement: SymmetricSecurityBindingElement и AsymmetricSecurityBindingElement. При получении привязки безопасности из коллекции необходимо привести к одному из этих типов, чтобы правильно задать MaxClockSkew свойство. В следующем примере используется объект WSHttpBinding, который использует объект SymmetricSecurityBindingElement. Для списка, указывающего, какой тип привязки безопасности использовать в каждой системной привязке, смотрите в разделе Системные привязки.
Создать пользовательскую привязку с новым значением смещения часов в коде
Предупреждение
Добавьте ссылки на следующие пространства имен в коде: System.ServiceModel.Channels, System.ServiceModel.Description, System.Security.Permissions, и System.ServiceModel.Security.Tokens.
Создайте экземпляр WSHttpBinding класса и задайте для нее режим SecurityMode.Messageбезопасности.
Создайте новый экземпляр BindingElementCollection класса, вызвав CreateBindingElements метод.
Используйте метод Find класса BindingElementCollection, чтобы найти элемент привязки безопасности.
При использовании Find метода приведение к фактическому типу. В приведенном ниже примере выполняется приведение к типу SymmetricSecurityBindingElement .
MaxClockSkew Задайте свойство элемента привязки безопасности.
Создайте ServiceHost с соответствующим типом службы и базовым адресом.
Используйте метод AddServiceEndpoint, чтобы добавить конечную точку и включить CustomBinding.
// This method returns a custom binding created from a WSHttpBinding. Alter the method // to use the appropriate binding for your service, with the appropriate settings. public static Binding CreateCustomBinding(TimeSpan clockSkew) { WSHttpBinding standardBinding = new WSHttpBinding(SecurityMode.Message, true); CustomBinding myCustomBinding = new CustomBinding(standardBinding); SymmetricSecurityBindingElement security = myCustomBinding.Elements.Find<SymmetricSecurityBindingElement>(); security.LocalClientSettings.MaxClockSkew = clockSkew; security.LocalServiceSettings.MaxClockSkew = clockSkew; // Get the System.ServiceModel.Security.Tokens.SecureConversationSecurityTokenParameters SecureConversationSecurityTokenParameters secureTokenParams = (SecureConversationSecurityTokenParameters)security.ProtectionTokenParameters; // From the collection, get the bootstrap element. SecurityBindingElement bootstrap = secureTokenParams.BootstrapSecurityBindingElement; // Set the MaxClockSkew on the bootstrap element. bootstrap.LocalClientSettings.MaxClockSkew = clockSkew; bootstrap.LocalServiceSettings.MaxClockSkew = clockSkew; return myCustomBinding; } private void Run() { // Create a custom binding using the method defined above. The MaxClockSkew is set to 30 minutes. Binding customBinding= CreateCustomBinding(TimeSpan.FromMinutes(30)); // Create a ServiceHost instance, and add a metadata endpoint. // NOTE When using Visual Studio, you must run as administrator. Uri baseUri = new Uri("http://localhost:1008/"); ServiceHost sh = new ServiceHost(typeof(Calculator), baseUri); // Optional. Add a metadata endpoint. The method is defined below. AddMetadataEndpoint(ref sh); // Add an endpoint using the binding, and open the service. sh.AddServiceEndpoint(typeof(ICalculator), customBinding, "myCalculator"); sh.Open(); Console.WriteLine("Listening..."); Console.ReadLine(); } private void AddMetadataEndpoint(ref ServiceHost sh) { Uri mex = new Uri(@"http://localhost:1001/metadata/"); ServiceMetadataBehavior sm = new ServiceMetadataBehavior(); sm.HttpGetEnabled = true; sm.HttpGetUrl = mex; sh.Description.Behaviors.Add(sm); }' This method returns a custom binding created from a WSHttpBinding. Alter the method ' to use the appropriate binding for your service, with the appropriate settings. Public Shared Function CreateCustomBinding(ByVal clockSkew As TimeSpan) As Binding Dim standardBinding As WSHttpBinding = New WSHttpBinding(SecurityMode.Message, True) Dim myCustomBinding As CustomBinding = New CustomBinding(standardBinding) Dim security As SymmetricSecurityBindingElement = _ myCustomBinding.Elements.Find(Of SymmetricSecurityBindingElement)() security.LocalClientSettings.MaxClockSkew = clockSkew security.LocalServiceSettings.MaxClockSkew = clockSkew ' Get the System.ServiceModel.Security.Tokens.SecureConversationSecurityTokenParameters Dim secureTokenParams As SecureConversationSecurityTokenParameters = _ CType(security.ProtectionTokenParameters, SecureConversationSecurityTokenParameters) ' From the collection, get the bootstrap element. Dim bootstrap As SecurityBindingElement = secureTokenParams.BootstrapSecurityBindingElement ' Set the MaxClockSkew on the bootstrap element. bootstrap.LocalClientSettings.MaxClockSkew = clockSkew bootstrap.LocalServiceSettings.MaxClockSkew = clockSkew Return myCustomBinding End Function Private Sub Run() ' Create a custom binding using the method defined above. The MaxClockSkew is set to 30 minutes. Dim customBinding As Binding = CreateCustomBinding(TimeSpan.FromMinutes(30)) ' Create a ServiceHost instance, and add a metadata endpoint. ' NOTE When using Visual Studio, you must run as administrator. Dim baseUri As New Uri("http://localhost:1008/") Dim sh As New ServiceHost(GetType(Calculator), baseUri) ' Optional. Add a metadata endpoint. The method is defined below. AddMetadataEndpoint(sh) ' Add an endpoint using the binding, and open the service. sh.AddServiceEndpoint(GetType(ICalculator), customBinding, "myCalculator") sh.Open() Console.WriteLine("Listening...") Console.ReadLine() End Sub Private Sub AddMetadataEndpoint(ByRef sh As ServiceHost) Dim mex As New Uri("http://localhost:1011/metadata/") Dim sm As New ServiceMetadataBehavior() sm.HttpGetEnabled = True sm.HttpGetUrl = mex sh.Description.Behaviors.Add(sm) End Sub
Чтобы установить MaxClockSkew в конфигурации
<Создайте элемент привязки> и задайте
nameатрибут соответствующим значением. Следующий пример задает для негоMaxClockSkewBindingзначение .Добавьте элемент кодировки. В приведенном ниже примере добавляется textMessageEncoding<.>
<Добавьте элемент безопасности> и задайте
authenticationModeатрибут соответствующим параметрам. Атрибут в следующем примере установлен наKerberos, чтобы указать, что служба использует аутентификацию Windows.<Добавьте localServiceSettings> и задайте атрибут
maxClockSkewзначением в виде"##:##:##". В следующем примере устанавливается значение 7 минут. При необходимости добавьте <localServiceSettings> и установите атрибутmaxClockSkewна соответствующее значение.Добавьте элемент транспорта. В следующем примере используется <httpTransport>.
Для безопасной беседы параметры безопасности должны устанавливаться на начальной загрузке в элементе <secureConversationBootstrap>.
<bindings> <customBinding> <binding name="MaxClockSkewBinding"> <textMessageEncoding /> <security authenticationMode="Kerberos"> <localClientSettings maxClockSkew="00:07:00" /> <localServiceSettings maxClockSkew="00:07:00" /> <secureConversationBootstrap> <localClientSettings maxClockSkew="00:30:00" /> <localServiceSettings maxClockSkew="00:30:00" /> </secureConversationBootstrap> </security> <httpTransport /> </binding> </customBinding> </bindings>