C# WCF服务中的用户名身份验证不起作用

C# WCF服务中的用户名身份验证不起作用,c#,wcf,authentication,C#,Wcf,Authentication,因此,我对WCF非常陌生,我需要一个基本的用户名或基于证书的身份验证方案来实现一些基本的安全性,以便只允许从我的应用程序使用该服务。总之,为了保持简短,这是我的配置,所以 <system.serviceModel> <bindings> <wsHttpBinding> <binding name="wsHttpBinding"> <security> <message clientCre

因此,我对WCF非常陌生,我需要一个基本的用户名或基于证书的身份验证方案来实现一些基本的安全性,以便只允许从我的应用程序使用该服务。总之,为了保持简短,这是我的配置,所以

  <system.serviceModel>
<bindings>
  <wsHttpBinding>
    <binding name="wsHttpBinding">
      <security>
        <message clientCredentialType="UserName"/>
      </security>
    </binding>
  </wsHttpBinding>
</bindings>
<client>
  <endpoint binding="wsHttpBinding" bindingConfiguration="wsHttpBinding"
    contract="uConnect.Web.IUConnectService" name="wsHttpBindingEndpoint" />
</client>
<behaviors>
  <serviceBehaviors>
    <behavior name="">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
      <serviceCredentials>
        <serviceCertificate findValue="CN=tempCert" storeLocation="CurrentUser" />
        <userNameAuthentication userNamePasswordValidationMode="Custom"
          customUserNamePasswordValidatorType="uConnect.Web.AuthValidation, uConnect.Web" />
      </serviceCredentials>
    </behavior>
  </serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
我已经学习了一些教程,我相信所有的配置都是正确的。然而,问题不是服务不起作用,而是工作正常。问题是,我可以访问我的服务合同和调用方法,而无需提供用户名/密码。但是,如果我用属性[PrincipalPermissionSecurityAction.Demand,Authenticated=true]装饰我的类,那么当我尝试访问它时,它将崩溃。现在,这可能是因为我实际上没有经过身份验证,或者完全是其他原因。但抛出的所有异常并不是我所期望的SecurityException

最后一件事,到目前为止我看到的所有教程都显示您提供了用户名/密码,例如

myService.ClientCredentials.UserName.UserName = "username";
myService.ClientCredentials.UserName.Password = "p@ssw0rd";

但是,当我将WCF契约引用添加到我的解决方案时,它是作为System.Web.Services.Protocols.SoapHttpClientProtocol类型的类提供的,它不提供属性ClientCredentials。关于如何继续并使一个简单的身份验证方案工作,有什么想法吗?

这篇文章可能发布得晚了,但我也遇到了同样的问题,结果是我的验证器类逻辑做得不太好。这是我的解决办法

 public override void Validate(string userName, string password)
    {
        if (null == userName || null == password)
        {
            throw new ArgumentNullException();
        }

        if (!(userName == "test1" && password == "1tset") && !(userName == "test2" && password == "2tset"))
        {
            throw new SecurityTokenException("Unknown Username or Incorrect Password");
        }
    }
 public override void Validate(string userName, string password)
    {
        if (null == userName || null == password)
        {
            throw new ArgumentNullException();
        }

        if (!(userName == "test1" && password == "1tset") && !(userName == "test2" && password == "2tset"))
        {
            throw new SecurityTokenException("Unknown Username or Incorrect Password");
        }
    }