WCF安全认证

pdi*_*ddy 8 .net c# wcf-security

我有一个简单的服务,我尝试设置身份验证.在客户端上,我希望用户输入他们的Windows用户帐户.WCF将使用客户端提供的用户名/密码,并根据Windows身份验证对其进行身份验证.

这是我的服务器app.config

 <system.serviceModel>
    <services>
      <service name="WcfService.Service1" behaviorConfiguration="WcfService.Service1Behavior">
        <host>
          <baseAddresses>
            <add baseAddress = "http://localhost:8731/Design_Time_Addresses/WcfService/Service1/" />
          </baseAddresses>
        </host>
        <endpoint address ="" binding="wsHttpBinding" contract="WcfService.IService1">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WcfService.Service1Behavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="True" />

          <serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode = "Windows"/>
          </serviceCredentials>

        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
Run Code Online (Sandbox Code Playgroud)

这是我的客户端app.config

<system.serviceModel>
    <bindings>
        <wsHttpBinding>
          <binding name="WSHttpBinding_IService1">

              <security mode = "Message">
                <message  clientCredentialType = "UserName"/>
              </security>

            </binding>
        </wsHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://localhost:8731/Design_Time_Addresses/WcfService/Service1/"
            binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService1"
            contract="ServiceReference1.IService1" name="WSHttpBinding_IService1">
            <identity>
                <dns value="localhost" />
            </identity>
        </endpoint>
    </client>
</system.serviceModel>
Run Code Online (Sandbox Code Playgroud)

这是我在客户端的代码

ServiceReference1.Service1Client client = new WcfAuthentication.ServiceReference1.Service1Client();

client.ClientCredentials.UserName.UserName = "mywindowsusername";
client.ClientCredentials.UserName.Password = "mywindowsuserpassword";
Console.WriteLine(client.GetData(5));
Run Code Online (Sandbox Code Playgroud)

但我总是得到这个例外:

{"无法打开安全通道,因为与远程端点的安全协商失败.这可能是由于用于创建通道的EndpointAddress中缺少或错误指定的EndpointIdentity.请验证EndpointAddress指定或暗示的EndpointIdentity是否正确识别了远程端点."} {"安全令牌请求包含无效或格式错误的元素."}

Ron*_*erg 7

看起来您是单独(手动)生成服务和客户端配置.使用svcutil或Visual Studio的"添加服务引用" 从服务生成客户端配置通常是个好主意.这样您就知道您获得了与服务配置相对应的客户端配置.

您想要的是什么,但WCF不允许您在使用时以纯文本形式传输您的用户名/密码令牌wsHttpBinding.这意味着您必须使用https托管服务或使用服务证书.是一篇有更多细节的帖子.

但我也想知道为什么你会想要这样的东西.使用集成Windows身份验证可能更好.这甚至是默认设置wsHttpBinding.这样您就不需要您的客户端输入他们的Windows用户名/密码.