我在IIS 8上托管了一个使用wsHttpBinding的简单WCF服务。我希望能够控制用户(域帐户)有权访问该服务。我怎样才能做到这一点?也许有几种方法可以做到这一点。我可以在web.config文件中定义帐户,还是在IIS中设置它?
答案 0 :(得分:1)
您可以使用PrincipalPermission来控制它。
看看这个答案: WCF security with Domain Groups
在这里你可以赶上msdn: http://msdn.microsoft.com/en-us/library/ms735093(v=vs.110).aspx
答案 1 :(得分:1)
您可以使用自定义身份验证器。
您需要从System.IdentityModel.Selectors命名空间继承UserNamePasswordValidator。
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>
这是您必须实施的基础知识。然后,您可以在Authenticate / Authorize方法中限制允许哪些用户调用Web服务方法。