【发布时间】:2016-03-02 20:37:44
【问题描述】:
我一直试图让这个工作几个小时,但没有任何运气。我正在尝试创建一个具有验证的 WCF Web 服务。我希望服务的消费者被要求做:
ServiceReference1.XServiceClient client = new ServiceReference1.XServiceClient();
client.ClientCredentials.UserName.UserName = "username";
client.ClientCredentials.UserName.Password = "password";
在他可以调用任何服务方法之前。我发现我必须创建一个 CustomUserNamePasswordValidator,所以我在解决方案中创建了类库项目以包含 Custom Validator 类。我只是想验证它是否有效。
namespace XServices
{
public class CustomUserNameValidator : UserNamePasswordValidator
{
public override void Validate(string username, string password)
{
if (!(username == "test" && password == "password"))
{
throw new FaultException("Invalid username or password!");
}
}
}
}
然后我尝试对 WCF 项目中的 web.config 文件进行必要的更改以支持它。不幸的是,这是我遇到的第一个麻烦。
这是我现在的 web.config 文件。
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<!-- connection strings ommitted for security reasons -->
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<customErrors mode="Off"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- 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="true"/>
</behavior>
<behavior name="CustomValidator">
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="CustomUserNameValidator.XServices.CustomUserNameValidator, CustomUserNameValidator"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<wsHttpBinding>
<binding name="Binding1">
<security mode="Message">
<message clientCredentialType="UserName" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
MSDN 文档非常不清楚 customUserNamePasswordValidatorType 的工作原理。 https://msdn.microsoft.com/en-us/library/aa702565(v=vs.110).aspx 的例子完全掩盖了它,所以我不知道我是否做得正确。更糟糕的是,如果您为该参数输入的内容不正确,它不会引发错误。它只是默默地忽略它。长话短说,我的自定义验证器的 Validate 方法没有被调用。我不知道为什么,经过数小时的谷歌搜索,我还没有找到任何有效的方法。请帮忙。
【问题讨论】:
标签: c# wcf authentication