我找到了基于此链接和此的解决方案。
第一个是在一个名为CustomUserNameValidator的类中覆盖方法 Validate ,该类继承自System.IdentityModel.Selectors.UserNamePasswordValidator:
Imports System.IdentityModel.Selectors
Imports System.ServiceModel
Imports System.Net
Public Class CustomUserNameValidator
Inherits UserNamePasswordValidator
Public Overrides Sub Validate(userName As String, password As String)
If Nothing = userName OrElse Nothing = password Then
Throw New ArgumentNullException()
End If
If Not (userName = "user" AndAlso password = "password") Then
Dim exep As New AddressAccessDeniedException("Incorrect user or password")
exep.Data("HttpStatusCode") = HttpStatusCode.Unauthorized
Throw exep
End If
End Sub
End Class
诀窍是将异常“HttpStatusCode”的属性更改为 HttpStatusCode.Unauthorized
第二个是在 App.config 中创建serviceBehavior如下:
<behaviors>
<endpointBehaviors>
<behavior name="HttpEnableBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="SimpleServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="Service.CustomUserNameValidator, Service"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
最后,我们必须指定 webHttpBinding 的配置并将其应用于端点:
<bindings>
<webHttpBinding>
<binding name="basicAuthBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Basic" realm=""/>
</security>
</binding>
</webHttpBinding>
</bindings>
<service behaviorConfiguration="SimpleServiceBehavior" name="Service.webService">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/webService" />
</baseAddresses>
</host>
<endpoint address="http://localhost:8000/webService/restful" binding="webHttpBinding" bindingConfiguration="basicAuthBinding" contract="Service.IwebService" behaviorConfiguration="HttpEnableBehavior"/>
</service>