2017-06-16 34 views
0

是否可以創建多個端點,這些端點將使用他們自己的用戶名/密碼進行身份驗證? (每個端點有自己的憑證)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

這類似於this question。據我所知,這在WCF中是不可能的,因爲你認證服務的訪問權限,而不是特定的端點。