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

时间:2015-09-08 23:56:42

标签: c# wcf authentication

所以我对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>

这是我的自定义验证类,现在使用硬编码的用户名/密码组合方法

namespace uConnect.Web
{
class AuthValidation : UserNamePasswordValidator
{
    public override void Validate(string userName, string password)
    {
        if (userName != "test" || password != "test")
            throw new SecurityException("Error: username/password combination invalid.");
    }
}
}

我已经关注了几个教程,我相信一切都配置正确。但问题不在于服务不起作用,它运行正常。问题是我可以访问我的服务合同并调用方法而无需提供用户名/密码。但是,如果我用属性[PrincipalPermission(SecurityAction.Demand, Authenticated = true)]装饰我的类,那么当我尝试访问它时它会崩溃。现在这可能是因为我实际上没有经过身份验证,或者完全没有其他任何东西。但抛出的所有异常都不是我期待的SecurityException

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

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

但是当我将WCF合同引用添加到我的解决方案时,它被提供为类型System.Web.Services.Protocols.SoapHttpClientProtocol的类,它不提供属性ClientCredentials。关于我应该如何进行并获得简单的身份验证方案的任何想法?

1 个答案:

答案 0 :(得分:0)

这可能是迟到但我遇到了同样的问题,结果我的验证器类逻辑做得不好。这是我的解决方案

 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");
        }
    }
相关问题