I've found a solution related to IT technology based on this
link and
this.
The first step is to override the Validate method in a class called CustomUserNameValidator, which inherits from 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.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>