【发布时间】:2013-12-10 08:05:39
【问题描述】:
我在 IIS 8 上托管了一个使用 wsHttpBinding 的简单 WCF 服务。我希望能够控制哪些用户(域帐户)可以访问该服务。我怎样才能做到这一点?也许有几种方法可以做到这一点。我可以在 web.config 文件中定义帐户还是在 IIS 中进行设置?
【问题讨论】:
标签: .net wcf .net-4.5 wcf-binding wcf-security
我在 IIS 8 上托管了一个使用 wsHttpBinding 的简单 WCF 服务。我希望能够控制哪些用户(域帐户)可以访问该服务。我怎样才能做到这一点?也许有几种方法可以做到这一点。我可以在 web.config 文件中定义帐户还是在 IIS 中进行设置?
【问题讨论】:
标签: .net wcf .net-4.5 wcf-binding wcf-security
你可以使用 PrincipalPermission 来控制它。
看看这个答案: WCF security with Domain Groups
在这里您可以了解 msdn: http://msdn.microsoft.com/en-us/library/ms735093(v=vs.110).aspx
【讨论】:
您可以使用自定义身份验证器。
您需要从 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 服务方法。
【讨论】: