Как установить максимальную разницу в показаниях часов
Если настройки времени в двух компьютерах различаются, возможен сбой критичных по времени функций. Чтобы устранить такую возможность, можно задать для свойства MaxClockSkew значение TimeSpan. Это свойство предусмотрено в двух классах.
![]() |
---|
Важно. Для безопасного диалога изменения свойства MaxClockSkew должны производиться на этапе начальной загрузки службы или клиента. Чтобы это сделать, необходимо задать данное свойство в SecurityBindingElement, возвращаемом BootstrapSecurityBindingElement. |
Чтобы изменить это свойство в одной из привязок, предоставляемых системой, необходимо найти элемент привязки безопасности в коллекции привязок и задать для свойства MaxClockSkew новое значение. От класса SecurityBindingElement наследуют два класса: SymmetricSecurityBindingElement и AsymmetricSecurityBindingElement. При извлечении привязки безопасности из коллекции необходимо приведение к одному из этих типов, чтобы правильно задать свойство MaxClockSkew. В следующем примере используется привязка WSHttpBinding, которая использует класс SymmetricSecurityBindingElement. Список с указанием, какой тип привязки безопасности следует использовать в каждой привязке, предоставляемой системой, см. в разделе Привязки, предоставляемые системой.
Создание пользовательской привязки с новым значением разницы в показаниях часов в коде
-
Примечание. Добавьте в код ссылки на следующие пространства имен: System.ServiceModel.Channels, System.ServiceModel.Description, System.Security.Permissions и System.ServiceModel.Security.Tokens. Создайте новый экземпляр класса WSHttpBinding и задайте для него режим безопасности 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 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("https://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("https://localhost:1011/metadata/") Dim sm As New ServiceMetadataBehavior() sm.HttpGetEnabled = True sm.HttpGetUrl = mex sh.Description.Behaviors.Add(sm) End Sub
// 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("https://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(@"https://localhost:1001/metadata/"); ServiceMetadataBehavior sm = new ServiceMetadataBehavior(); sm.HttpGetEnabled = true; sm.HttpGetUrl = mex; sh.Description.Behaviors.Add(sm); }
Задание MaxClockSkew в конфигурации
Создайте элемент customBinding Element в разделе элемента <Bindings>.
Создайте элемент <binding> и задайте требуемое значение атрибута name. В следующем примере задается значение
MaxClockSkewBinding
.Добавьте элемент кодирования. В приведенном ниже примере добавляется элемент textMessageEncoding element.
Добавьте элемент security Element of customBinding и задайте требуемое значение атрибута authenticationMode. В следующем примере для этого атрибута задается значение Kerberos, чтобы задать, что в службе используется проверка подлинности Windows.
Добавьте localServiceSettings element и задайте значение атрибута maxClockSkew в формате "##:##:##". В следующем примере задается значение 7 минут. Если требуется, добавьте localServiceSettings element и задайте для атрибута maxClockSkew соответствующее значение.
Добавьте транспортный элемент. В следующем примере используется httpTransport element.
Для безопасного диалога параметры безопасности должны задаваться при начальной загрузке в элементе 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>
См. также
Справочник
LocalClientSecuritySettings
LocalServiceSecuritySettings
CustomBinding
Основные понятия
Как создавать пользовательскую привязку с использованием элемента SecurityBindingElement