WCF多个端点,每个端点都有自己的用户名/密码

时间:2017-06-16 18:11:02

标签: wcf

是否可以创建多个端点,这些端点将使用自己的用户名/密码进行身份验证? (每个端点都有自己的凭据)

我有一个端点的示例,工作正常。我不知道如何使用相同的身份验证方法添加多个端点。

我的例子:

String adress1 = "http://localhost/CalculatorService";
        String adress2 = "http://localhost/CalculatorService/en1/";
        Uri[] baseAddresses = { new Uri(adress1) };

        ServiceHost host = new ServiceHost(typeof(CalculatorService), baseAddresses);
        ContractDescription contDesc = ContractDescription.GetContract(typeof(ICalculator));

        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;
        smb.HttpGetUrl = new Uri(adress1);

        host.Description.Behaviors.Add(cd);
        host.Description.Behaviors.Add(smb);

        EndpointAddress adr1 = new EndpointAddress(baseAddresses[0]);

        ServiceEndpoint en1 = new ServiceEndpoint(contDesc);
        en1.Binding = b1;
        en1.Address = adr1;
        en1.Name = "en1";


        ServiceEndpoint en2 = new ServiceEndpoint(contDesc);
        en2.Binding = new BasicHttpBinding();
        en2.Address = new EndpointAddress(adress2);
        en2.Name = "en2";

        host.AddServiceEndpoint(en1);
        host.AddServiceEndpoint(en2);

        host.Open();

身份验证类:

class CustomUserNameValidator : UserNamePasswordValidator
  {
    public override void Validate(string userName, string password)
    {
      if (userName.ToLower() != "test" || password.ToLower() != "test")
      {
        throw new SecurityTokenException("Unknown Username or Incorrect Password");
      }
    }
  }

接口/类:

[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);
  }


  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;
    }
  }

1 个答案:

答案 0 :(得分:1)

这与this question类似。根据我的知识,这在WCF中是不可能的,因为您验证了对服务的访问,而不是对特定端点的访问。