When I try to call a WCF service I am getting the following message «An error occurred when verifying security for the message.»
When I remove the custom authenication the service works no problem. I can’t figure out though what I have misconfigured in my web.config. Any insight would be appreciated.
<system.serviceModel>
<services>
<service behaviorConfiguration="NAThriveExtensions.nableAPIBehavior"
name="NAThriveExtensions.nableAPI">
<endpoint
address=""
binding="basicHttpBinding"
bindingConfiguration="basicHttpBinding_Secure"
contract="NAThriveExtensions.InableAPI">
</endpoint>
<endpoint
address="mex"
binding="mexHttpsBinding"
contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="NAThriveExtensions.nableAPIBehavior">
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
<serviceCredentials>
<userNameAuthentication
userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType= "NAThriveExtensions.Authentication, NAThriveExtensions" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="basicHttpBinding_Secure">
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
asked Sep 21, 2010 at 23:26
Matt KlepeisMatt Klepeis
1,7241 gold badge14 silver badges25 bronze badges
I was getting this same error message and it turned out to be due to a time difference between my workstation machine and the server hosting the WCF service. The server was about 10 minutes behind my machine and WCF security doesn’t seem to like that very much.
To find the root problem I turned on serviceSecurityAuditing in the server’s config file. Add the following to the configuration/system.serviceModel/behaviors/serviceBehaviors/behavior section for your service:
<serviceSecurityAudit
auditLogLocation="Application"
serviceAuthorizationAuditLevel="Failure"
messageAuthenticationAuditLevel="Failure"
suppressAuditFailure="true"/>
The following site was helpful in figuring this out:
http://blogs.microsoft.co.il/blogs/urig/archive/2011/01/23/wcf-quot-an-error-occurred-when-verifying-security-for-the-message-quot-and-service-security-audit.aspx
answered Mar 7, 2013 at 23:10
3
Another cause of this message is when some of your machines are not synchronized in time. WCF, by default, allows a five-minute gap; beyond this, it throws an error if things are out of synch.
The solution is to synch all your machines. time.windows.com
is notorious for not working, so I suggest using something else. (If you’re in a corporate environment, a local domain controller may be the correct choice here.)
answered Jan 31, 2014 at 16:30
ashes999ashes999
9,85715 gold badges72 silver badges120 bronze badges
3
This ended up being an problem on the consuming side, not with the service itself. Software AG’s webMethods 8 was consuming this server but there was no Security Handler added to the service so the credentials were not being added to the header thus resulting the in the aforementioned error.
answered Oct 8, 2010 at 16:24
Matt KlepeisMatt Klepeis
1,7241 gold badge14 silver badges25 bronze badges
2
I had a similar issue.
I was building my datetime formatted strings using my local time, but my service/server was expecting GMT.
I needed to get the GMT time (JAVA):
final Date currentTime = new Date();
final SimpleDateFormat sdf =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.000Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(currentTime));
answered Mar 17, 2019 at 20:42
Pablo ChvxPablo Chvx
1,75917 silver badges31 bronze badges
I was getting the same error on my IIS 7.5 server. I forgot to add Read permission on the certificate’s private key to the app pool virtual account (e.g. IIS AppPoolASP.NET v4.0).
For info, whilst testing various combinations of accounts and permissions, I noticed that the app pool needed to be recycled to lose access to the key, once it had been retrieved once.
(0x80131501 — An error occurred when verifying security for the message.)
answered Apr 8, 2013 at 5:57
ssg31415926ssg31415926
1,0172 gold badges13 silver badges21 bronze badges
I was getting the same error and none of the above help for me.
I finally tracked it down to connectionStrings in a parent web.config (my service was deployed to a child application to an admin site).
Yes sounds ridiculous, but as soon as I wrapped the connection strings in the parent web.config with a location element all started working.
For clarity, in parent web.config, I changed this
<connectionStrings>
<add name="..." />
</connectionStrings>
to this
<location path="." inheritInChildApplications="false">
<connectionStrings>
<add name="..." />
</connectionStrings>
</location>
Note this error also resulted in this very unhelpful serviceSecurityAudit log message:
Message authentication failed.
Service: …
Action: http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT
ClientIdentity:
ActivityId:
ArgumentNullException: Value cannot be null.
Parameter name: manager
answered Sep 6, 2016 at 12:30
I was getting the same error. I forgot to add Read permission on the membership database aspnetdb to the (IIS APPPOOLDefaultAppPool).
Message authentication failed. Service:….
Action: http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT
ClientIdentity:
ActivityId:
SqlException: Cannot open database «aspnetdb» requested by the login. The login failed.
Login failed for user ‘IIS
APPPOOLDefaultAppPool’.
answered Dec 19, 2016 at 7:24
The username and password is the server you connection,not your
system login username and password.
answered Dec 23, 2015 at 9:05
MapleStoryMapleStory
6183 gold badges11 silver badges21 bronze badges
Содержание
- Error occurred verifying security message
- Answered by:
- Question
- Answers
- Произошла ошибка при проверке безопасности сообщения
- 7 ответов
- Soap Fault: [InvalidSecurity]: An error occurred when verifying security for the message
- Comments
- «An error occurred when verifying security for the message» — WCF certificate-based authentication
- Error occurred verifying security message
- Question
- Answers
Error occurred verifying security message
Answered by:
Question
I have a WCF service and it is http not https, it is added in . now the team update the service and the new link is https,
once I changed the endpoint address to https, I got error «The provided URI schema ‘https’ is invalid; expected ‘http’. Parameter name:via»
services app WebConfig:
Answers
Hi Khalid Salameh,
As far as I think, you could switch from wsHttpBinding to basicHttpBinding to fix this.
Do you need SOAP 1.1 or application/soap+xml; charset=utf-8? Because SOAP 1.1 specification says that the request must have text/xml as the media type. application/soap+xml is media type for SOAP 1.2. Forcing WCF to use SOAP 1.1 with application/soap+xml (= invalid SOAP) would require bigger changes than changing the binding. You will need some custom message encoder or perhaps transport channel.
More details,you could refer to below article:
Источник
Произошла ошибка при проверке безопасности сообщения
когда я пытаюсь вызвать службу WCF я получаю следующее сообщение «произошла ошибка при проверке безопасности сообщения.»
когда я удаляю пользовательскую аутентификацию, служба работает без проблем. Я не могу понять, что я неправильно сконфигурировал в своей сети.конфиг. Любое понимание будет оценено.
7 ответов
Я получал это же сообщение об ошибке, и оказалось, что это связано с разницей во времени между моей рабочей станцией и сервером, на котором размещена служба WCF. Сервер был около 10 минут позади моей машины, и WCF security, похоже, не очень нравится.
чтобы найти корневую проблему, я включил serviceSecurityAuditing в конфигурационном файле сервера. Добавьте в конфигурацию/систему следующее.serviceModel / поведение / serviceBehaviors / раздел поведение для вашего обслуживания:
следующий сайт был полезен в выяснении этого:
другая причина это сообщение, когда некоторые из ваших машин не синхронизированы во времени. WCF по умолчанию допускает пятиминутный разрыв; кроме того, он выдает ошибку, если что-то не синхронизировано.
раствор для синхронизации всех ваших машин. time.windows.com славится тем, что не работает, поэтому я предлагаю использовать что-то другое. (Если вы находитесь в корпоративной среде, локальный контроллер домена может быть правильный выбор.)
Это оказалось проблемой на стороне потребления, а не с самой службой. Webmethods 8 программного обеспечения AG потреблял этот сервер, но не было никакого обработчика безопасности, добавленного к службе, поэтому учетные данные не были добавлены в заголовок, что привело к вышеупомянутой ошибке.
Я получаю ту же ошибку на моем сервере IIS 7.5. Я забыл добавить разрешение на чтение на закрытый ключ сертификата в виртуальный аккаунт пула приложений (например, IIS AppPoolASP.NET v4.0).
для информации, тестируя различные комбинации учетных записей и разрешений, я заметил, что пул приложений необходимо переработать, чтобы потерять доступ к ключу, как только он был извлечен один раз.
(0x80131501-произошла ошибка при проверке безопасности сообщение.)
Я получал ту же ошибку, и ни одна из вышеперечисленных помощь для меня.
Я, наконец, отследил его до connectionStrings в родительской сети.config (моя служба была развернута в дочернем приложении на сайте администратора).
Да, звучит смешно, но как только я завернул строки подключения в родительской сети.config с элементом location все начали работать.
для ясности, в родительской сети.config я изменил это
обратите внимание, что эта ошибка также привела к этому очень бесполезному serviceSecurityAudit сообщение:
ошибка проверки подлинности сообщения.
Услуга. .
Действие:http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT
ClientIdentity:
Значение activityid:
ArgumentNullException: значение не может быть null.
Имя параметра: менеджер
Я получал ту же ошибку. Я забыл добавить разрешение на чтение в базу данных членства aspnetdb в (IIS APPPOOLDefaultAppPool).
ошибка проверки подлинности сообщения. Услуга.
SqlException: не удается открыть базу данных «aspnetdb», запрошенную логином. Ошибка входа в систему.
ошибка входа в систему для IIS пользователя Пула средством’.
имя пользователя и пароль сервер подключения,а не ваши имя пользователя и пароль для входа в систему.
Источник
Soap Fault: [InvalidSecurity]: An error occurred when verifying security for the message
I’m new to SOAtest and just trying to get a simple WSDL operation to go to an endpoint and return a response. We require a Basic authentication with a Username and Password, which I provide. I keep getting this error no matter how basic the operation request I use.
I am an avid SoapUI user and these work without a problem. I’ve compared the SoapUI raw request with the SOAtest request information and everything looks correct. I’ve even found the system clock can sometimes cause this error, but that didn’t work either.
Not sure if rebooting will help, I will try that next although I believe I just came from a reboot. This did run once correctly but I cannot get it to run again.
PLEASE help! As this seems to be such a minor issue, but I’m not able to get any real work done. It’s got me dead in the water.
I look forward to any help or suggestions to get this working.
Thanks a lot in advance!
An error occurred when verifying security for the message
This is a Microsoft error message, typically returned from web services implemented using the .NET WCF web service stack. SOAtest will show the message from the SOAP Fault in the traffic viewer and Quality Task view.
The actual reason for such errors is generally not returned back to the client for security reasons. In order to determine the actual reason (as opposed to you or I guessing) there should be a way to enable logging on the web service and then check those logs for the answer.
I’ve even found the system clock can sometimes cause this error, but that didn’t work either.
I usually see something like this for web services that use WS-Security, where the request has a WS-Security header containing a timestamp. If the timing skew between the timestamp in the message and the server’s clock is too great then this would trigger the service to return a security error. .NET WCF services have a «maxClockSkew» property that can be configured in its security configuration.
We require a Basic authentication with a Username and Password, which I provide
I’d recommend double checking that. For example, you were thinking system clock may be a factor but Basic Authentication doesn’t involve any timestamps being sent in any requests. Maybe the authentication is really sent as something else like Digest or NTLM authentication?
Something else you can try is by selecting the «.NET WCF HTTP» transport instead of the «HTTP 1.0/1.1» transport. If you provide the SOAP Client with a WSDL for your .NET web service then then SOAP Client will apply the message and transport security to the message automatically when the test is executed, including adding of any WS-Security headers. There are general username and password fields in the settings for the «.NET WCF HTTP» transport.
Источник
«An error occurred when verifying security for the message» — WCF certificate-based authentication
I am attempting to set up cert-based client authentication in a WCF service. I am using .NET 4.7.2.
I am testing both the host app and the client on the same machine. The intended behaviour is that the client uses a cert retrieved from a machine store to authenticate against the service.
I can see that channelFactory does have the desired certificate set. I can see that it has a private key set, when I view it via certmgr. I can see that its root cert is in the machine’s root store.
This is how the client connects:
This is how the service is set up:
I have removed a lot of code from both of the above that I understand to be unrelated.
The connection fails with the message «An error occurred when verifying security for the message». I don’t know what is wrong or how to investigate it.
As suggested by stuartd, I added a security audit behavior. I did this programmatically as follows:
If the security isn’t set in the client, the following is logged:
MessageSecurityException: Security processor was unable to find a security header in the message. This might be because the message is an unsecured fault or because there is a binding mismatch between the communicating parties. This can occur if the service is configured for security and the client is not using security.
If it is set as above, then nothing is logged and it doesn’t connect.
Источник
Error occurred verifying security message
Question
I have a WCF service and it is http not https, it is added in . now the team update the service and the new link is https,
once I changed the endpoint address to https, I got error «The provided URI schema ‘https’ is invalid; expected ‘http’. Parameter name:via»
services app WebConfig:
Answers
Hi Khalid Salameh,
As far as I think, you could switch from wsHttpBinding to basicHttpBinding to fix this.
Do you need SOAP 1.1 or application/soap+xml; charset=utf-8? Because SOAP 1.1 specification says that the request must have text/xml as the media type. application/soap+xml is media type for SOAP 1.2. Forcing WCF to use SOAP 1.1 with application/soap+xml (= invalid SOAP) would require bigger changes than changing the binding. You will need some custom message encoder or perhaps transport channel.
More details,you could refer to below article:
Источник
- Remove From My Forums
-
Question
-
User-1952516322 posted
Hi all,
I have a WCF service and it is http not https, it is added in <customBinding>… now the team update the service and the new link is https,
once I changed the endpoint address to https, I got error «The provided URI schema ‘https’ is invalid; expected ‘http’. Parameter name:via»
services app WebConfig:
<system.serviceModel> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="false" /> <bindings> <customBinding> <binding name="CustomBinding_Service" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"> <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16" messageVersion="Default" writeEncoding="utf-8"> <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> </textMessageEncoding> <httpTransport manualAddressing="false" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" allowCookies="false" authenticationScheme="Anonymous" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" keepAliveEnabled="true" maxBufferSize="2147483647" proxyAuthenticationScheme="Anonymous" realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false" useDefaultWebProxy="true" /> </binding> </customBinding> </bindings> <client> <endpoint address="https://xxxService.svc" binding="customBinding" bindingConfiguration="CustomBinding_Service" contract="OrgServiceReference.IOrgService" name="CustomBinding_Service"> <identity> <userPrincipalName value="admin@ab.local" /> </identity> </endpoint> </client> </system.serviceModel>
Thanks.
Answers
-
User1535942433 posted
Hi Khalid Salameh,
As far as I think, you could switch from wsHttpBinding to basicHttpBinding to fix this.
Do you need SOAP 1.1 or application/soap+xml; charset=utf-8? Because SOAP 1.1 specification says that the request must have text/xml as the media type. application/soap+xml is media type for SOAP 1.2. Forcing WCF to use SOAP 1.1 with application/soap+xml
(= invalid SOAP) would require bigger changes than changing the binding. You will need some custom message encoder or perhaps transport channel.More details,you could refer to below article:
https://stackoverflow.com/questions/8087515/wcf-service-using-basichttpbinding-is-still-sending-content-type-text-xml
Best regards,
Yijing Sun
-
Marked as answer by
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by
Произошла ошибка при проверке безопасности сообщения
когда я пытаюсь вызвать службу WCF я получаю следующее сообщение «произошла ошибка при проверке безопасности сообщения.»
когда я удаляю пользовательскую аутентификацию, служба работает без проблем. Я не могу понять, что я неправильно сконфигурировал в своей сети.конфиг. Любое понимание будет оценено.
<system.serviceModel>
<services>
<service behaviorConfiguration="NAThriveExtensions.nableAPIBehavior"
name="NAThriveExtensions.nableAPI">
<endpoint
address=""
binding="basicHttpBinding"
bindingConfiguration="basicHttpBinding_Secure"
contract="NAThriveExtensions.InableAPI">
</endpoint>
<endpoint
address="mex"
binding="mexHttpsBinding"
contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="NAThriveExtensions.nableAPIBehavior">
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
<serviceCredentials>
<userNameAuthentication
userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType= "NAThriveExtensions.Authentication, NAThriveExtensions" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="basicHttpBinding_Secure">
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
7 ответов
Я получал это же сообщение об ошибке, и оказалось, что это связано с разницей во времени между моей рабочей станцией и сервером, на котором размещена служба WCF. Сервер был около 10 минут позади моей машины, и WCF security, похоже, не очень нравится.
чтобы найти корневую проблему, я включил serviceSecurityAuditing в конфигурационном файле сервера. Добавьте в конфигурацию/систему следующее.serviceModel / поведение / serviceBehaviors / раздел поведение для вашего обслуживания:
<serviceSecurityAudit
auditLogLocation="Application"
serviceAuthorizationAuditLevel="Failure"
messageAuthenticationAuditLevel="Failure"
suppressAuditFailure="true"/>
следующий сайт был полезен в выяснении этого:
http://blogs.microsoft.co.il/blogs/urig/archive/2011/01/23/wcf-quot-an-error-occurred-when-verifying-security-for-the-message-quot-and-service-security-audit.aspx
другая причина это сообщение, когда некоторые из ваших машин не синхронизированы во времени. WCF по умолчанию допускает пятиминутный разрыв; кроме того, он выдает ошибку, если что-то не синхронизировано.
раствор для синхронизации всех ваших машин. time.windows.com
славится тем, что не работает, поэтому я предлагаю использовать что-то другое. (Если вы находитесь в корпоративной среде, локальный контроллер домена может быть правильный выбор.)
Это оказалось проблемой на стороне потребления, а не с самой службой. Webmethods 8 программного обеспечения AG потреблял этот сервер, но не было никакого обработчика безопасности, добавленного к службе, поэтому учетные данные не были добавлены в заголовок, что привело к вышеупомянутой ошибке.
Я получаю ту же ошибку на моем сервере IIS 7.5. Я забыл добавить разрешение на чтение на закрытый ключ сертификата в виртуальный аккаунт пула приложений (например, IIS AppPoolASP.NET v4.0).
для информации, тестируя различные комбинации учетных записей и разрешений, я заметил, что пул приложений необходимо переработать, чтобы потерять доступ к ключу, как только он был извлечен один раз.
(0x80131501-произошла ошибка при проверке безопасности сообщение.)
Я получал ту же ошибку, и ни одна из вышеперечисленных помощь для меня.
Я, наконец, отследил его до connectionStrings в родительской сети.config (моя служба была развернута в дочернем приложении на сайте администратора).
Да, звучит смешно, но как только я завернул строки подключения в родительской сети.config с элементом location все начали работать.
для ясности, в родительской сети.config я изменил это
<connectionStrings>
<add name="..." />
</connectionStrings>
в это
<location path="." inheritInChildApplications="false">
<connectionStrings>
<add name="..." />
</connectionStrings>
</location>
обратите внимание, что эта ошибка также привела к этому очень бесполезному serviceSecurityAudit сообщение:
ошибка проверки подлинности сообщения.
Услуга. :..
Действие:http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT
ClientIdentity:
Значение activityid:
ArgumentNullException: значение не может быть null.
Имя параметра: менеджер
Я получал ту же ошибку. Я забыл добавить разрешение на чтение в базу данных членства aspnetdb в (IIS APPPOOLDefaultAppPool).
ошибка проверки подлинности сообщения. Услуга.:…
действие:http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT
ClientIdentity:
значение activityid:
SqlException: не удается открыть базу данных «aspnetdb», запрошенную логином. Ошибка входа в систему.
ошибка входа в систему для IIS пользователя
Пула средством’.
имя пользователя и пароль сервер подключения,а не ваши
имя пользователя и пароль для входа в систему.
- Remove From My Forums
-
Вопрос
-
Добрый день, господа. Подскажите, куда копать.
Windows Server 2008 R2 32 bit.
В IIS развернут узел, — сайт web-forms,с аутентификацией по сертификату.
Есть ссылка на wcf, от которой получает данные.
При запускe на iisexpress через VS2013 в режиме отладки — все хорошо. После публикации и размещения на вышеуказанном сервере — вот такая ошибка:
Ошибка сервера в приложении ‘/’.
An error occurred when verifying security for the message.
Описание: Необработанное исключение при выполнении текущего веб-запроса. Изучите трассировку стека для получения дополнительных сведений о данной ошибке и о вызвавшем ее фрагменте кода.
Сведения об исключении: System.ServiceModel.FaultException: An error occurred when verifying security for the message.
Ошибка источника:
Необработанное исключение при выполнении текущего веб-запроса. Информацию о происхождении и месте возникновения исключения можно получить, используя следующую трассировку стека исключений.
Трассировка стека:
[FaultException: An error occurred when verifying security for the message.] [MessageSecurityException: Незащищенное или неправильно защищенное сообщение об ошибке было получено от другой стороны. Код ошибки и описание см. внутреннее исключение.] System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +10818447 System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +336 Service_portal.ServiceReference.IHotLine.GetData(String ProcName, CustomParams[] _params, String DBname) +0 Service_portal.ContactClass.AddParams(String name, String value, String proc, String dbnum) +276 Service_portal.ControlDistionary.Page_Load(Object sender, EventArgs e) +59 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51 System.Web.UI.Control.OnLoad(EventArgs e) +92 System.Web.UI.Control.LoadRecursive() +54 System.Web.UI.Control.LoadRecursive() +145 System.Web.UI.Control.LoadRecursive() +145 System.Web.UI.Control.LoadRecursive() +145 System.Web.UI.Control.LoadRecursive() +145 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772
-
Перемещено
26 марта 2015 г. 11:36
-
Перемещено
Ответы
-
Здравствуйте,
Похоже на ошибку с WCF, как одна из возможных причин, если время клиента и сервера отличается более чем на 10 минут, то не удастся пройти
проверку безопасности .
Best Regards, Andrei …
Microsoft Certified Professional-
Предложено в качестве ответа
Tomas Lilov
26 марта 2015 г. 12:30 -
Помечено в качестве ответа
Иван ПродановMicrosoft contingent staff, Moderator
31 марта 2015 г. 7:50
-
Предложено в качестве ответа
pavel.kozak |
|
Статус: Участник Группы: Участники
|
Добрый день. Пока вопрос туманный, т.к. нет полного понимания происходящего. Есть устоявшийся проект с использованием КриптоПро 4.0 + КриптоПро .NET (6893 работает стабильно), используется для подключения к Web сервису по WCF (Гост 2012). Начали миграцию проекта на NET Core 3.x + .NET Framework 4.7.2, до этого была смесь Core 2.x + .NET Framework 4.6.1. Предположительно(т.к. ставим средствами VS 2019, что он там ещё тянет под сомнением) после установки на машину SDK Core 3.x + SDK .NET Framework 4.8 + соответственно сам коре и фреймфорк получаем проблемы с WCF в существующем проекте, т.е. изменений в сам проект ещё не внесли, только установили Core + FrameWork посвежее. При попытке подключения к сервису с авторизацией по ГОСТ ключу 2012, получаем ошибку: Коллекция шифрования маркера не поддерживает алгоритм «urn:ietf:params:xml:ns:cpxmlsec:algorithms:transport-gost2012-256». Т.е. поведение, как будто не установлен КриптоПро .NET. Переустанавливаем весь комплект КриптоПро + КриптоПро .NET. Результата нет. Проверено на двух машинах Windows 10 И Windows Server 2012 R2. Интересный момент, попробовали поднять версию Крипто Про .NET (SDK Крипто Про .NET поднимали соответственно) до 7132 Выше указанная ошибка на этапе подключения пропала, но при вызове получили другую ошибку: Попробую узнать какую версию SDK Крипто Про использует поставщик Web Сервиса. Отредактировано пользователем 10 января 2020 г. 10:25:30(UTC) |
|
|
Максим Коллегин |
|
Статус: Сотрудник Группы: Администраторы Сказал «Спасибо»: 21 раз |
Обновлять КриптоПро .Net при обновлении .Net нужно с вероятностью 90% |
Знания в базе знаний, поддержка в техподдержке |
|
|
WWW |
pavel.kozak |
|
Статус: Участник Группы: Участники
|
Спасибо. Да, форк видели но не решились, поэтому и смесь Core 98% + Framework 2%. Сосредоточимся тогда на вопросе почему не работает с .NET КриптоПро 7132. Попробуем ещё раз пересобрать с новым SDK 7132, может что-то упустил. Насколько важно, что бы .NET КриптоПро был одинаковый на клиенте и на сервере? |
|
|
Максим Коллегин |
|
Статус: Сотрудник Группы: Администраторы Сказал «Спасибо»: 21 раз |
Автор: pavel.kozak Насколько важно, что бы .NET КриптоПро был одинаковый на клиенте и на сервере? Не должны быть одинаковыми. Постарайтесь собрать трассировку WCF — посмотрим. |
Знания в базе знаний, поддержка в техподдержке |
|
|
WWW |
pavel.kozak |
|
Статус: Участник Группы: Участники
|
Пересобрал с последним SDK. Если по трейсу, то получается следующий порядок: Пытаемся вызвать удаленную функцию TestAuthentication Поставщик токена безопасности открыт. Генерирование исключения Протоколу безопасности не может проверить входящее сообщение. Конец. Тот же код с предыдущей версией работает корректно. Пока не возможности проверить на чистой машине свежий SDK КриптоПро на старом фреймвекке. |
|
|
pavel.kozak |
|
Статус: Участник Группы: Участники
|
Автор: Максим Коллегин Не должны быть одинаковыми. Оказывается, все таки есть зависимости. https://br.so-ups.ru/Pub…ws=%5Bobject%20Object%5D Как-то упустил эту новость. Теперь тупичок, придется ещё одну кашу делать и запускать прослойку на машине со старым фремвёрком и старым .NET КриптоПро :(. |
|
|
Максим Коллегин |
|
Статус: Сотрудник Группы: Администраторы Сказал «Спасибо»: 21 раз |
Странно, ничего не слышал про это. Изучим вопрос. |
Знания в базе знаний, поддержка в техподдержке |
|
|
WWW |
Артём Макаров |
|
Статус: Сотрудник Группы: Участники Сказал(а) «Спасибо»: 4 раз |
Добрый день. Подскажите, какой сейчас target framework задан в проекте? Какая привязка используется? Если возможно приложите файл конфигурации клиента (app.config). Можете приложить wcf trace и messssage log с ошибкой? Как собирать можно посмотреть тут — https://docs.microsoft.c…figuring-message-logging Код:
|
Техническую поддержку оказываем тут |
|
|
|
pavel.kozak |
|
Статус: Участник Группы: Участники
|
Автор: Максим Коллегин Странно, ничего не слышал про это. Изучим вопрос. Насколько успел узнать, тикет поставщиком сервиса создавался, примерно в то время когда они писали эту новость. |
|
|
pavel.kozak |
|
Статус: Участник Группы: Участники
|
Автор: Артём Макаров Подскажите, какой сейчас target framework задан в проекте? Проверяли несколько, поведение и ошибка одинаковые и на 4.6.2, 4.7.1, 4.8. Автор: Артём Макаров Какая привязка используется? WSHttpBinding Это пример со стенда, в основном проекте вместо конфига настройка из кода идет. Но значения те же. <wsHttpBinding> <endpoint address=»http://br.so-ups.ru:8091/PersonalApi/PersonalApiService.svc/ByCertificate» Автор: Артём Макаров Можете приложить wcf trace и messssage log с ошибкой? Я отправлю в личку, то что собрали в пятницу с нашими настройками, если не подойдет, то позже сниму с вашими рекомендациями. |
|
|
Пользователи, просматривающие эту тему |
Guest |
Быстрый переход
Вы не можете создавать новые темы в этом форуме.
Вы не можете отвечать в этом форуме.
Вы не можете удалять Ваши сообщения в этом форуме.
Вы не можете редактировать Ваши сообщения в этом форуме.
Вы не можете создавать опросы в этом форуме.
Вы не можете голосовать в этом форуме.
Hi,
I am getting the following error when I try to consume a Web Service.
«An error occurred when verifying security for the message.»
I have gone through many web sites and tried to implement their suggestions, but the error still persists. So can anyone help me out in this regard.
Thank you
Comments
Could you please «Improve Question» and add to your question:
The end point you are using
The code you use to consume the web service (if it’s third party make sure to remove the real url)
Hi,
Thanks for the reply
The error was raised because the system time and the internet time were not in sync. The system time and the internet time were few minutes apart. I changed the system time and the error was solved.
Glad you got it sorted ^_^
Please update the question and add «[Solved]» to the front of the title
Do what Andy suggests but I would also guess there is more to the error message, or even an InnerException.
Hi,
Thanks for the reply
The error was raised because the system time and the internet time were not in sync. The system time and the internet time were few minutes apart. I changed the system time and the error was solved.
Interesting. Please post that as the solution so this no longer shows unanswered. Glad to see you got it resolved.
I have a problem connecting to my WCF service with clientCredentialType="UserName"
.
When I run the code below I get an error
FaultException: An error occurred when verifying security for the message.
When playing around with some of the binding values I also get Access is denied.
.
Fiddler says there is no authorization header and I cannot find the username or password in the request either.
Here are excerpts from my config:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<services>
<service name="InventoryServices.MobileAPI" behaviorConfiguration="customBehaviour">
<endpoint address=""
binding="basicHttpBinding"
bindingConfiguration="secureHttpBinding"
contract="InventoryServices.IMobileAPI"/>
<endpoint address="mex"
binding="mexHttpsBinding"
contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="customBehaviour">
<serviceSecurityAudit auditLogLocation="Application" serviceAuthorizationAuditLevel="Failure" messageAuthenticationAuditLevel="Failure" suppressAuditFailure="true" />
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType="InventoryLibrary.Helpers.UserAuthentication,InventoryLibrary"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<bindings>
<basicHttpBinding>
<binding name="secureHttpBinding">
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="Basic" proxyCredentialType="Basic" realm="MyRealm"/>
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
My username/password validator looks like so:
public class UserAuthentication : UserNamePasswordValidator {
public override void Validate(string userName, string password) {
EntitiesContext db = new EntitiesContext();
db.Logs.Add(new DomainModels.Log() {
DateLogged = DateTime.Now,
Message = "hit auth",
Type = DomainModels.LogType.Info
});
db.SaveChanges();
try {
if (userName == "test" && password == "test123") {
Console.WriteLine("Authentic User");
}
}
catch (Exception ex) {
throw new FaultException("Unknown Username or Incorrect Password");
}
}
}
I have this as a simple test on my service:
[OperationContract]
[XmlSerializerFormat]
void Test();
[PrincipalPermission(SecurityAction.Demand, Name = "test")]
public void Test() {
}
I have a self signed SSL certificate on my server and I can access my service/metadata.
Then I have added a service reference in a console application, and attempt to connect to the service with this code below:
class Program {
static void Main(string[] args) {
Stuff.InitiateSSLTrust();
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.Transport;
binding.Security.Transport.Realm = "MyRealm";
ServiceReference1.MobileAPIClient serviceProxy = new ServiceReference1.MobileAPIClient(binding, new EndpointAddress("https://xx.xx.xx.xx/InventoryServices.MobileApi.svc"));
serviceProxy.ClientCredentials.UserName.UserName = "test";
serviceProxy.ClientCredentials.UserName.Password = "test123";
try {
var a = serviceProxy.Login("a", "b");
}
catch (Exception ex) {
var ex2 = ex;
}
}
}
public class Stuff {
public static void InitiateSSLTrust() {
try {
//Change SSL checks so that all checks pass
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(
delegate { return true; }
);
}
catch (Exception ex) {
}
}
}
I’ve checked the event viewer on the server and this error appears with each request:
MessageSecurityException: Security processor was unable to find a security header in the message. This might be because the message is an unsecured fault or because there is a binding mismatch between the communicating parties. This can occur if the service is configured for security and the client is not using security.