具有授权的 WCF 找不到自定义验证函数

本文关键字:自定义 验证 函数 找不到 WCF 授权 | 更新日期: 2023-09-27 18:33:03

我用这个属性创建了一个服务:

namespace WcfServiceLibrary1
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetProductName(int productID);
        [OperationContract]
        int GetProductQty(int productID);
        [OperationContract]
        string GetCategoryName(int productID);
        // TODO: Add your service operations here
    }

}

我应该实现一个授权函数,如你在这里看到的:

namespace WcfServiceLibrary1
{
    public class CustomValidator : UserNamePasswordValidator
   {
       public override void Validate(string userName, string password)
       {
           if (userName == "test" && password == "test")
               return;
           throw new SecurityTokenException(
               "Unknown Username or Password");
       }
    }
}

appsetting中,我定义了验证函数的Behavior和其他属性,如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <services>
      <service name="WcfServiceLibrary1.Service1" behaviorConfiguration="WcfServic">
        <host>
          <baseAddresses>
            <add baseAddress = "http://localhost:8733/WcfServiceLibrary1.Service1.svc" />
          </baseAddresses>
        </host>
        <!-- Service Endpoints -->
        <!-- Unless fully qualified, address is relative to base address supplied above -->
        <endpoint address="" binding="wsHttpBinding" bindingConfiguration="SafeServiceConf" contract="WcfServiceLibrary1.IService1">
          <!-- 
              Upon deployment, the following identity element should be removed or replaced to reflect the 
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity 
              automatically.
          -->
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <!-- Metadata Endpoints -->
        <!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. --> 
        <!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WcfServic">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
          <serviceCredentials>
            <userNameAuthentication
                 userNamePasswordValidationMode="Custom"
                 customUserNamePasswordValidatorType="WcfServiceLibrary1.CustomValidator.Validate,WcfServiceLibrary1"
                                                                      />
          </serviceCredentials>
        </behavior>
        <behavior>
          <!-- To avoid disclosing metadata information, 
          set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
          <!-- To receive exception details in faults for debugging purposes, 
          set the value below to true.  Set to false before deployment 
          to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <wsHttpBinding>
        <binding name="SafeServiceConf" maxReceivedMessageSize="65536">
          <readerQuotas maxStringContentLength="65536" maxArrayLength="65536"
          maxBytesPerRead="65536" />
          <security mode="TransportWithMessageCredential">
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
  </system.serviceModel>
</configuration>

在这一部分中,我定义了要授权的自定义函数

 <serviceCredentials>
                <userNameAuthentication
                     userNamePasswordValidationMode="Custom"
                     customUserNamePasswordValidatorType="WcfServiceLibrary1.CustomValidator.Validate,WcfServiceLibrary1"
                                                                          />
              </serviceCredentials>

但是当我运行该服务时,我收到此错误:

System.TypeLoadException: Could not load type 'WcfServiceLibrary1.CustomValidator.Validate' from assembly 'WcfServiceLibrary1'.
   at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type)
   at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName)
   at System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark)
   at System.Type.GetType(String typeName, Boolean throwOnError)
   at System.ServiceModel.Configuration.UserNameServiceElement.ApplyConfiguration(UserNamePasswordServiceCredential userName)
   at System.ServiceModel.Configuration.ServiceCredentialsElement.ApplyConfiguration(ServiceCredentials behavior)
   at System.ServiceModel.Configuration.ServiceCredentialsElement.CreateBehavior()
   at System.ServiceModel.Description.ConfigLoader.LoadBehaviors[T](ServiceModelExtensionCollectionElement`1 behaviorElement, KeyedByTypeCollection`1 behaviors, Boolean commonBehaviors)
   at System.ServiceModel.Description.ConfigLoader.LoadServiceDescription(ServiceHostBase host, ServiceDescription description, ServiceElement serviceElement, Action`1 addBaseAddress, Boolean skipHost)
   at System.ServiceModel.ServiceHostBase.LoadConfigurationSectionInternal(ConfigLoader configLoader, ServiceDescription description, ServiceElement serviceSection)
   at System.ServiceModel.ServiceHostBase.ApplyConfiguration()
   at System.ServiceModel.ServiceHost.ApplyConfiguration()
   at System.ServiceModel.ServiceHostBase.InitializeDescription(UriSchemeKeyedCollection baseAddresses)
   at System.ServiceModel.ServiceHost.InitializeDescription(Type serviceType, UriSchemeKeyedCollection baseAddresses)
   at System.ServiceModel.ServiceHost..ctor(Type serviceType, Uri[] baseAddresses)
   at Microsoft.Tools.SvcHost.ServiceHostHelper.CreateServiceHost(Type type, ServiceKind kind)
   at Microsoft.Tools.SvcHost.ServiceHostHelper.OpenService(ServiceInfo info)

具有授权的 WCF 找不到自定义验证函数

配置

中的这一行看起来不正确。 customUserNamePasswordValidatorType="WcfServiceLibrary1.CustomValidator.Validate,WcfServiceLibrary1"

WcfServiceLibrary1.CustomValidator.Validate是一个方法,但它需要一个类型,因此它试图实例化验证。尝试将其替换为

customUserNamePasswordValidatorType="WcfServiceLibrary1.CustomValidator,WcfServiceLibrary1"