От другой стороны получен незащищенный или неправильно защищенный отказ. (При работе с SAML)

Я новичок в веб-службе WCF. в настоящее время я работаю над федеративным веб-сервисом с привязкой федерации (SAML). Я воспользовался примерами MSDN в «Поставщике токенов SAML». Но проблема в том, что я не могу использовать сервис, когда я его использую, он выдает «От другой стороны получена незащищенная или неправильно защищенная ошибка» с внутренним исключением как «Произошла ошибка при обработке маркеров безопасности в сообщении».

это мой файл веб-конфигурации на стороне сервера

 <?xml version="1.0"?>
  <configuration>
   <system.web>
     <compilation debug="true" targetFramework="4.0"/>
   </system.web>
   <system.serviceModel>
     <bindings>
       <wsFederationHttpBinding>
          <binding name="Binding1">
            <security mode="Message" >
              <message negotiateServiceCredential ="false" issuedKeyType ="AsymmetricKey" 
                             issuedTokenType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1">
              </message>
            </security>
          </binding>
          <!-- Binding that expect SAML tokens with Asymmetric proof keys -->
          <binding name="Binding2">
             <security mode="Message">
                <message negotiateServiceCredential ="false"
                             issuedTokenType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1">
                </message>
             </security>
          </binding>
       </wsFederationHttpBinding>
    </bindings>
    <services>
    <!--<service name="MobileInterfaceWCFService.MobileService" behaviorConfiguration="MobileInterfacebehavior">
            <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basic_http" contract="MobileInterfaceWCFService.IMobileInterface" />
        </service>
        <service name ="MobileInterfaceWCFService.MobileService" behaviorConfiguration="MobileInterfaceWCFService.Service1Behavior">
            <endpoint address="" binding="wsHttpBinding" contract="MobileInterfaceWCFService.IMobileInterface" bindingName="wsHttpBinding_ITMNetWCFService_ITMMobileSharedWebService" bindingConfiguration="wsHttpBinding_ITMNetWCFService_ITMMobileSharedWebService">
                <identity>
                    <dns value="localhost" />
                </identity>
            </endpoint>
        </service> -->
        <service name ="MobileInterfaceWCFService.MobileService" behaviorConfiguration="MobileInterfaceWCFService.SamlTokenBehavior">
            <endpoint address="" binding="wsFederationHttpBinding" contract="MobileInterfaceWCFService.IMobileInterface" bindingName="Binding1" bindingConfiguration="Binding1">
                <identity>
                    <dns value="localhost" />
                </identity>
            </endpoint>
        </service>
    </services>
    <client>
        <endpoint address="http://host-root/MobileSharedWebService/MobileSharedWebService.svc" binding="wsHttpBinding" bindingConfiguration="wsHttpBinding_ITMNetWCFService_ITMMobileSharedWebService" contract="ServiceReference1.ITMMobileSharedWebService" name="wsHttpBinding_ITMNetWCFService_ITMMobileSharedWebService">
            <identity>
                <dns value="localhost"/>
            </identity>
        </endpoint>
    </client>
    <behaviors>
        <serviceBehaviors>
            <behavior name="MobileInterfacebehavior">
                <!--<serviceMetadata httpGetEnabled="true" />-->
            </behavior>
            <behavior name="MobileInterfaceWCFService.Service1Behavior">
                <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
            <!--    <serviceMetadata httpGetEnabled="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="false"/>
            </behavior>

            <behavior name="MobileInterfaceWCFService.SamlTokenBehavior">
                <serviceMetadata httpGetEnabled="true"  /> 
                <!-- 
                    The serviceCredentials behavior allows one to define a service certificate.
                    A service certificate is used by a client to authenticate the service and provide message protection.
                    This configuration references the "localhost" certificate installed during the setup instructions.
                    -->
                <serviceCredentials>
                    <!-- Set allowUntrustedRsaIssuers to true to allow self-signed, asymmetric key based SAML tokens -->
                    <issuedTokenAuthentication allowUntrustedRsaIssuers ="false" >
                        <!-- Add Alice to the list of certs trusted to issue SAML tokens -->
                        <knownCertificates>
                            <add storeLocation="LocalMachine" 
                                 storeName="TrustedPeople"
                                 x509FindType="FindBySubjectName"
                                 findValue="Alice"/>
                            </knownCertificates>
                    </issuedTokenAuthentication>
                    <serviceCertificate storeLocation="LocalMachine"
                                        storeName="My"
                                        x509FindType="FindBySubjectName"
                                        findValue="localhost"  />
                </serviceCredentials>
            </behavior>
        </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <handlers accessPolicy="Read, Script" />
    <security>
        <authentication>
            <anonymousAuthentication enabled="true" />
            <windowsAuthentication enabled="true" />
        </authentication>
    </security>
    <asp enableParentPaths="true" />
</system.webServer>

<system.diagnostics>
        <sources>
            <source name="System.ServiceModel"
                    switchValue="Information, ActivityTracing"
                    propagateActivity="true">
                <listeners>
                    <add name="traceListener"
                        type="System.Diagnostics.XmlWriterTraceListener"
                        initializeData= "c:\log\Traces.svclog" />
                </listeners>
            </source>
        </sources>
    </system.diagnostics>

     </configuration>

вот мой конфигурационный файл на стороне потребителя

<?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <system.serviceModel>
    <bindings>
        <wsFederationHttpBinding>
         <binding name="Binding1_IMobileInterface"  >
            <security mode="Message">
                <message issuedKeyType="AsymmetricKey"      issuedTokenType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1"
                    negotiateServiceCredential="false"  >   
                </message>
                </security>
            </binding>
        </wsFederationHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://localhost/WCF_MobileInterface/MobileService.svc"
            binding="wsFederationHttpBinding" bindingConfiguration="Binding1_IMobileInterface"
            contract="ServiceReference1.IMobileInterface" name="Binding1_IMobileInterface">
            <identity>
                <dns value="localhost" />
            </identity>
        </endpoint>
    </client>
</system.serviceModel>
  </configuration>

Примечание. Я перепробовал все решения, связанные с ошибкой/проблемой одного типа, как в stackoverflow, так и в Google, но не смог решить проблему

Любая быстрая помощь будет оценена

заранее спасибо


person dreamweiver    schedule 04.02.2013    source источник


Ответы (1)


Я устранил ошибку, о которой упоминал выше. Мне пришлось добавить следующий тег под моим wsfederationbinding

<allowedAudienceUris>
    <add allowedAudienceUri="http://localhost/WCF_MobileInterface/MobileService.svc"/>
</allowedAudienceUris>

uri, упомянутый в атрибуте allowedAudienceuri, является хост-службой WCF.

На самом деле я узнал, что это была ошибка, когда я добавил следующий тег в файл веб-конфигурации службы WCF (),

<serviceSecurityAudit  auditLogLocation="Application" serviceAuthorizationAuditLevel="Failure" messageAuthenticationAuditLevel="Failure" suppressAuditFailure="true" /> 

под тегом поведения, который сопоставлялся с моим wsfederationbinding, этот тег регистрирует точное сообщение об ошибке в категории журнала приложений в средстве просмотра событий системы.

Примечание. Я включил трассировку на уровне сервера и потребителя, но сообщение об ошибке не выдавалось правильно. Но я обнаружил проблему, проверив журналы ошибок в средстве просмотра событий

надеюсь, что это поможет кому-то, кто борется с подобной ошибкой.

person dreamweiver    schedule 05.02.2013
comment
Был ли <allowedAudienceUris> добавлен в службу выдачи маркеров (STS) или в службу, которая была защищена STS? Я действительно борюсь с аналогичной проблемой и не могу добиться большого прогресса, потому что моя аутентификация состояний регистрации прошла успешно. stackoverflow.com/questions/20378081/ - person atconway; 04.12.2013
comment
@atconway: в раздел <allowedAudienceUris> была добавлена ​​служба выдачи токенов (STS), и служба хоста не имеет к этому никакого отношения. STS — это шлюз для целевой службы. Если служба шлюза или STS правильно настроены, то целевая служба может быть легко использована клиентским приложением. - person dreamweiver; 05.12.2013
comment
Если этот раздел опущен, предполагается ли, что «все» разрешены? Значение его использования создает операцию «белого списка»? Мне было трудно сказать из документации MSDN. - person atconway; 05.12.2013
comment
Тег <allowedAudienceUris> используется для указания того, какие все службы хоста доступны для службы токенов SAML, это не белый список для URL-адресов клиентов. вам просто нужно включить службу хоста/цели, которую вы хотите предоставить всем клиентам. - person dreamweiver; 05.12.2013