C# IIS托管的WCF服务&;使用Windows身份验证的SQL查询

C# IIS托管的WCF服务&;使用Windows身份验证的SQL查询,c#,wpf,wcf,silverlight,web-services,C#,Wpf,Wcf,Silverlight,Web Services,我对WCF相当陌生,但我有一个托管在IIS中的WCF服务,它对我们的SQL Server有几个查询。我正在使用带有WPF应用程序的WCF服务。我试图做的是允许windows身份验证从WPF客户端传递到WCF服务,再传递到SQL Server,以便SQL查询作为客户端用户执行。到目前为止,我一直在尝试以各种方式配置网站和主机 在我的WCF服务网站上,我有匿名身份验证=true(对于MEX)、ASP.NET模拟=true和Windows身份验证=true 在我的WCF服务Web.config中: &

我对WCF相当陌生,但我有一个托管在IIS中的WCF服务,它对我们的SQL Server有几个查询。我正在使用带有WPF应用程序的WCF服务。我试图做的是允许windows身份验证从WPF客户端传递到WCF服务,再传递到SQL Server,以便SQL查询作为客户端用户执行。到目前为止,我一直在尝试以各种方式配置网站和主机

在我的WCF服务网站上,我有匿名身份验证=true(对于MEX)、ASP.NET模拟=true和Windows身份验证=true

在我的WCF服务Web.config中:

<configuration>
  <system.web>
    <customErrors mode="Off"/>
    <authentication mode="Windows"/>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      </assemblies>
    </compilation>
  </system.web>
  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding maxReceivedMessageSize="5000000" name="WindowsSecurity">
          <readerQuotas maxDepth="200"/>
          <security mode="Transport">
            <transport clientCredentialType="Windows" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <services>
      <service name="ADATrackingService" behaviorConfiguration="ServiceBehavior">
        <endpoint address="" binding="wsHttpBinding" bindingConfiguration="WindowsSecurity"
          name="wsHttpEndpoint" contract="IADATrackingService" />
        <endpoint address="mex" binding="mexHttpsBinding" name="MexHttpsBindingEndpoint"
          contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
          <serviceAuthorization impersonateCallerForAllOperations="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>
  <connectionStrings>
    <add name="ADATrackingEntities" connectionString="metadata=res://*/EntityModel.ADATrackingModel.csdl|res://*/EntityModel.ADATrackingModel.ssdl|res://*/EntityModel.ADATrackingModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MYSERVER;initial catalog=ADATracking;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>
<configuration>
    <system.serviceModel>
      <behaviors>
        <endpointBehaviors>
          <behavior name="WindowsAuthentication">
            <clientCredentials>
              <windows allowedImpersonationLevel="Delegation"/>
            </clientCredentials>
          </behavior>
        </endpointBehaviors>
      </behaviors>
        <bindings>
            <wsHttpBinding>
                <binding name="wsHttpEndpoint" closeTimeout="00:01:00" openTimeout="00:01:00"
                    receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false"
                    transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferPoolSize="524288" maxReceivedMessageSize="5000000"
                    messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                    allowCookies="false">
                    <readerQuotas maxDepth="200" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <reliableSession ordered="true" inactivityTimeout="00:10:00"
                        enabled="false" />
                    <security mode="Transport">
                        <transport clientCredentialType="Windows" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="Windows" negotiateServiceCredential="true" />
                    </security>
                </binding>
            </wsHttpBinding>
        </bindings>
        <client>
            <endpoint address="https://MyService.svc"
                binding="wsHttpBinding" behaviorConfiguration="WindowsAuthentication" bindingConfiguration="wsHttpEndpoint"
                contract="ADATrackingService.IADATrackingService" name="wsHttpEndpoint">
                <identity>
                    <servicePrincipalName value="host/MyServer.com" />
                </identity>
            </endpoint>
        </client>
    </system.serviceModel>
</configuration>

然后在我的WPF客户端App.Config中我有:

<configuration>
  <system.web>
    <customErrors mode="Off"/>
    <authentication mode="Windows"/>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      </assemblies>
    </compilation>
  </system.web>
  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding maxReceivedMessageSize="5000000" name="WindowsSecurity">
          <readerQuotas maxDepth="200"/>
          <security mode="Transport">
            <transport clientCredentialType="Windows" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <services>
      <service name="ADATrackingService" behaviorConfiguration="ServiceBehavior">
        <endpoint address="" binding="wsHttpBinding" bindingConfiguration="WindowsSecurity"
          name="wsHttpEndpoint" contract="IADATrackingService" />
        <endpoint address="mex" binding="mexHttpsBinding" name="MexHttpsBindingEndpoint"
          contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
          <serviceAuthorization impersonateCallerForAllOperations="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>
  <connectionStrings>
    <add name="ADATrackingEntities" connectionString="metadata=res://*/EntityModel.ADATrackingModel.csdl|res://*/EntityModel.ADATrackingModel.ssdl|res://*/EntityModel.ADATrackingModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MYSERVER;initial catalog=ADATracking;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>
<configuration>
    <system.serviceModel>
      <behaviors>
        <endpointBehaviors>
          <behavior name="WindowsAuthentication">
            <clientCredentials>
              <windows allowedImpersonationLevel="Delegation"/>
            </clientCredentials>
          </behavior>
        </endpointBehaviors>
      </behaviors>
        <bindings>
            <wsHttpBinding>
                <binding name="wsHttpEndpoint" closeTimeout="00:01:00" openTimeout="00:01:00"
                    receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false"
                    transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferPoolSize="524288" maxReceivedMessageSize="5000000"
                    messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                    allowCookies="false">
                    <readerQuotas maxDepth="200" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <reliableSession ordered="true" inactivityTimeout="00:10:00"
                        enabled="false" />
                    <security mode="Transport">
                        <transport clientCredentialType="Windows" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="Windows" negotiateServiceCredential="true" />
                    </security>
                </binding>
            </wsHttpBinding>
        </bindings>
        <client>
            <endpoint address="https://MyService.svc"
                binding="wsHttpBinding" behaviorConfiguration="WindowsAuthentication" bindingConfiguration="wsHttpEndpoint"
                contract="ADATrackingService.IADATrackingService" name="wsHttpEndpoint">
                <identity>
                    <servicePrincipalName value="host/MyServer.com" />
                </identity>
            </endpoint>
        </client>
    </system.serviceModel>
</configuration>

我的服务调用只是使用允许模拟的元数据从SQL返回简单查询。每次我运行客户端并从我的服务中调用某个东西时,我都会在打开“NT Authority/ANONYMOUS LOGIN”的数据连接时出错,即使在IIS中设置了AnonymousAuthentication=false???任何帮助都将不胜感激。谢谢

[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public List<IndividualDisability> GetIndividualDisabilities()
{
    WindowsIdentity callerWindowsIdentity = ServiceSecurityContext.Current.WindowsIdentity;
    if (callerWindowsIdentity == null)
    {
        throw new InvalidOperationException
         ("The caller cannot be mapped to a Windows identity.");
    }
    using (callerWindowsIdentity.Impersonate())
    {
        using (var context = new ADATrackingEntities())
        {
            return context.IndividualDisabilities.OfType<IndividualDisability>().Include("ADACode").Include("Individual").Include("Disability").ToList();
        }
    }
}
[操作行为(模拟=模拟选项。必选)]
公共列表GetIndividualDisabilities()
{
WindowsIdentity调用者Windows Identity=ServiceSecurityContext.Current.WindowsIdentity;
if(callerWindowsIdentity==null)
{
抛出新的InvalidOperationException
(“调用方无法映射到Windows标识。”);
}
使用(CallerWindowIdentity.Impersonate())
{
使用(var context=new adatrackingenties())
{
返回context.IndividualDisabilities.OfType().Include(“ADACode”).Include(“个人”).Include(“残疾”).ToList();
}
}
}

在IIS中,是否已明确删除匿名身份验证?请执行以下操作:

  • 打开IIS管理器
  • 导航到您的WCF服务应用程序
  • 在功能视图中的IIS下,单击身份验证
  • 删除除Windows身份验证之外的任何身份验证方案。(默认情况下启用匿名。)
  • 为了帮助确保WPF应用程序不会以任何方式进行干扰,请首先使用wcftestclient进行测试

  • 打开开发人员命令窗口(开始菜单>程序>Microsoft Visual Studio 2010>Visual Studio工具>Visual Studio命令提示符(2010))
  • wcftestclienthttps://url.to/myservice.svc

  • 好吧,今天又浏览了一些。我终于让它工作了!问题是,在active directory中,我需要允许委托到SQL Server框。AD中有一个设置,您必须在web服务器盒上进行设置,以允许它委托到端口1433上SQl服务器盒上的SQl服务。我还必须确保在Web服务器上设置了kerebos身份验证。这篇博文准确地解释了我的情况,并帮助我从头到尾地工作:


    谢谢您的回复。我想我已经在IIS和服务中正确配置了一切。使用WCF测试客户端运行时,im现在收到错误:“要么未提供所需的模拟级别,要么提供的模拟级别无效。”啊哈!你有没有试过为你的模仿而努力编码?将以下内容添加到web.config中,以确保从服务到SQL server都很好:即使在对web.config中的值进行硬编码时,我也会收到一个错误。“登录到NT授权/匿名登录的SQL失败”。我在想,我可能需要在我的SQL框中配置一些东西??在仔细检查我的配置之后,我现在得到一个新的错误。登录到mydomain/machinename$的SQL失败,而不是我在web.config中输入要模拟的mydomain/username。我想知道为什么它试图以机器名连接到SQL Server??为了澄清我的Web服务器和SQL Server在不同的机器上。