2013-12-10 71 views
0

我有一個簡單的WCF服務託管在使用wsHttpBinding的IIS 8上。我希望能夠控制那些用戶(域帳戶)有權訪問該服務。我怎樣才能做到這一點?也許有幾種方法可以做到這一點。我可以在web.config文件中定義帳戶,還是可以在IIS中進行設置?wsHttpBinding,只允許某些帳戶訪問服務

+0

可能的重複http://stackoverflow.com/questions/13326365/best-way-to-limit-wcf-service-to-specific-user-accounts –

回答

1

你可以使用自定義的驗證器。

您需要從System.IdentityModel.Selectors命名空間繼承UserNamePasswordValidator

Sample from MSDN

public class ServiceValidator : UserNamePasswordValidator 
{ 
    public override void Validate(string userName, string password) 
    { 

     if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password)) 
     { 
      throw new SecurityTokenException("Username and password required"); 
     } 
     else 
     { 
      if (Authenticate(userName, password)) 
      { 
       // no need to do anything else if authentication was successful. the request will be redirected to the correct web service method. 
      } 
      else 
      { 
       throw new FaultException("Wrong username or password "); 
      } 
     } 

Web.config文件服務器:

<behaviors> 
    <serviceBehaviors> 
    <behavior name="SomeServiceBehavior"> 
     <serviceMetadata httpGetEnabled="true" /> 
     <serviceCredentials> 
     <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MyApp.ServiceValidator, MyApp" /> 
     <serviceCertificate findValue="CertificateNameHere" storeLocation="LocalMachine" storeName="TrustedPeople" x509FindType="FindBySubjectName" /> 
     </serviceCredentials> 
    </behavior> 
    </serviceBehaviors> 
</behaviors> 

<serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 
<bindings> 
    <wsHttpBinding> 
    <binding name="RequestUserName"> 
     <security mode="Message"> 
     <message clientCredentialType="UserName" /> 
     </security> 
    </binding> 
    </wsHttpBinding> 
</bindings> 

這是基本的東西你會^ h大街落實。然後,您可以在您的身份驗證/授權方法中限制哪些用戶應該被允許調用Web服務方法。

相關問題