【发布时间】:2016-07-10 16:03:08
【问题描述】:
这几天我一直在尝试解决这个问题。我知道我很接近,但无法完全弄清楚我错过了什么。
- 服务位于 IIS 上托管的网站中
- 网站的基本身份验证已启用,包括匿名身份验证在内的所有其他身份验证均已禁用。
- 我已创建自签名证书并设置了 https 绑定
- 我已经覆盖了 UsernamePasswordValidator 的 Validate 方法,但是当我附加一个断点时,它没有到达。所以我的问题很可能与此有关。
- 当我尝试在 https://localhost/Services/JobSiteService.svc/rest/get 访问我的服务方法时,由于收到 401 未经授权的错误,我不断提示我输入用户名和密码。
谁能看出我做错了什么?
下面的相应代码:
Web.Config
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpTransportSecurity">
<security mode="Transport">
<transport clientCredentialType="Basic" />
</security>
</binding>
</webHttpBinding>
</bindings>
<services>
<service name="Validity.WebService.JobSiteService" behaviorConfiguration="SecureRestBehavior">
<endpoint address="rest" binding="webHttpBinding" behaviorConfiguration="RESTBehavior" bindingConfiguration="webHttpTransportSecurity" contract="Validity.WebService.Contracts.IJobSiteService" />
<endpoint address="meta" binding="mexHttpsBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="SecureRestBehavior">
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="Validity.WebService.IdentityValidator, Validity.WebService" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="RESTBehavior" >
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="webHttpBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
服务合同:
[ServiceContract]
public interface IJobSiteService
{
[OperationContract]
[WebInvoke(Method="GET", ResponseFormat=WebMessageFormat.Json)]
List<JobSite> Get();
}
自定义验证器(它在命名空间“Validity.WebService”中,但是当我包含它时代码格式被破坏了。):
public override void Validate(string userName, string password)
{
using (var context = new ValidityContext())
{
using (var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)))
{
var user = userManager.Find(userName, password);
if (user == null)
{
var msg = String.Format("Unknown Username {0} or incorrect password {1}", userName, password);
throw new FaultException(msg);//the client actually will receive MessageSecurityException. But if I throw MessageSecurityException, the runtime will give FaultException to client without clear message.
}
else
{
SessionOperationContext.Current.Items["CurrentUser"] = user;
}
}
}
}
对此的任何帮助将不胜感激。
【问题讨论】:
-
您只显示了服务器端信息。客户端必须向 IIS 提供 Authorization 标头,因此请首先关注那里。
-
感谢 Crowcoder,看来问题在于 IIS 根据 Windows 凭据验证我的身份验证标头,而不是使用我的自定义验证方法。
标签: c# rest wcf iis-7.5 basic-authentication