我已经在代码中使用basicHttpBinding实现了用户名/密码身份验证。问题是,从客户端调用时不需要验证。我可以调用所有方法,就像没有在服务器端设置验证一样。我预计应该从客户端提供用户名和密码,否则这将无法正常工作。但是,它不是那样的。
在客户端,我只是添加了对Web服务的引用并启动了调用方法。
知道为什么会这样吗?
服务器代码:
String adress1 = "http://localhost/CalculatorService";
Uri[] baseAddresses = { new Uri(adress1) };
ServiceHost host = new ServiceHost(typeof(CalculatorService), baseAddresses);
ServiceCredentials cd = new ServiceCredentials();
cd.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
cd.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomUserNameValidator();
BasicHttpBinding b1 = new BasicHttpBinding();
b1.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
b1.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
host.Description.Behaviors.Add(cd);
host.Description.Behaviors.Add(smb);
EndpointAddress adr1 = new EndpointAddress(baseAddresses[0]);
ServiceEndpoint en1 = new ServiceEndpoint(ContractDescription.GetContract(typeof(ICalculator)));
en1.Binding = b1;
en1.Address = adr1;
host.Open();
用户名/密码验证类:
namespace ConsoleApplication1
{
class CustomUserNameValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if(userName.ToLower() != "test" || password.ToLower() != "test1")
{
throw new SecurityTokenException("Unknown Username or Incorrect Password");
}
}
}
}
接口:
namespace ConsoleApplication1
{
[ServiceContract]
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
[OperationContract]
double Subtract(double n1, double n2);
[OperationContract]
double Multiply(double n1, double n2);
[OperationContract]
double Divide(double n1, double n2);
}
}
类别:
namespace ConsoleApplication1
{
public class CalculatorService : ICalculator
{
public double Add(double n1, double n2)
{
return n1 + n2;
}
public double Subtract(double n1, double n2)
{
return n1 - n2;
}
public double Multiply(double n1, double n2)
{
return n1 * n2;
}
public double Divide(double n1, double n2)
{
return n1 / n2;
}
}
}
答案 0 :(得分:1)
我唯一忘记的是将端点添加到主机。
host.AddServiceEndpoint(en1);
在客户端,绑定应该是:
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ICalculator">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Basic"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
然后,致电:
WCFUserPass.CalculatorClient client = new WCFUserPass.CalculatorClient();
client.ClientCredentials.UserName.UserName = "test";
client.ClientCredentials.UserName.Password = "test";
var result = client.Add(1, 3);