wcf - 将对象注入(inject)自定义 WCF UserNamePassValidator - Autofac

标签 wcf dependency-injection wcf-security autofac

我有一个托管在 IIS 中的服务。它由 Web.config 配置。

我创建了一个自定义 UserNamePassValidator,如果我在 validate 方法中有逻辑,它就可以工作。但我想要另一个项目中的逻辑并使用 DI 注入(inject)如下。

public class UserNamePassValidator : System.IdentityModel.Selectors.UserNamePasswordValidator
{
    private readonly ISystemAuthentication _systemAuthentication;

    public UserNamePassValidator(ISystemAuthentication systemAuthentication)
    {
        _systemAuthentication = systemAuthentication;
    }

    public override void Validate(string userName, string password)
    {
        _systemAuthentication.Validate(userName, password))
    }
}

我正在使用 Autofac WCF 集成。
var builder = new ContainerBuilder();
builder.RegisterType<AuthenticationService>().As<IAuthenticationService>();
builder.Register(c => new SystemAuthentication()).As<ISystemAuthentication>();
builder.Register(c => new UserNamePassValidator(c.Resolve<ISystemAuthentication>()));
AutofacHostFactory.Container = builder.Build();

当我浏览到该服务时,我收到以下错误:
[MissingMethodException: No parameterless constructor defined for this object.]

web.config 行为;
 <userNameAuthentication
                 userNamePasswordValidationMode="Custom"
                 customUserNamePasswordValidatorType="MyNamespace.UserNamePassValidator, service" />

我已阅读以下相关帖子,但该示例是自托管服务:
How to inject an object into a WCF validator class

编辑
  <system.serviceModel>
    <services>
      <service behaviorConfiguration="Namespace.AuthenticationServiceBehaviour" name="Namespace.AuthenticationService" >
        <endpoint address="" binding="wsHttpBinding" contract="Namespace.IAuthenticationService" bindingConfiguration="SafeServiceConf">
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="Namespace.AuthenticationServiceBehaviour">
          <serviceMetadata httpGetEnabled="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="true" />
          <serviceCredentials>
            <serviceCertificate findValue="AuthenticationService" 
              storeLocation="LocalMachine"
              storeName="My" 
              x509FindType="FindBySubjectName" />
            <userNameAuthentication
              userNamePasswordValidationMode="Custom"
              customUserNamePasswordValidatorType="Namespace.UserNamePassValidator, Service" />
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <wsHttpBinding>
        <binding name="SafeServiceConf" maxReceivedMessageSize="65536">
          <readerQuotas maxStringContentLength="65536" maxArrayLength="65536" maxBytesPerRead="65536" />
          <security mode="Message">
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>

SystemAuthentication 类
public class SystemAuthentication : ISystemAuthentication
{
   public bool Validate(string userName, string password)
   {
       // removed code for abbreviation
       return true;
   }

WCF 身份验证服务
public class AuthenticationService : IAuthenticationService
    { 
        public bool Authenticate(string email, string password)
        {
            // removed for abbreviation
            return true;
        }
    }

最佳答案

在这篇文章的帮助下UserNamePasswordValidator: When DI and Framework collide

从我删除的 XML 配置中:

<userNameAuthentication
   userNamePasswordValidationMode="Custom"
   customUserNamePasswordValidatorType="MyNamespace.UserNamePassValidator, service" />

我将行为添加到 AutoFacHostFactory 服务主机
   IContainer container = builder.Build();
    AutofacHostFactory.Container = container;
    AutofacHostFactory.HostConfigurationAction = host =>
    {
        var auth = host.Credentials.UserNameAuthentication;
        auth.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
        auth.CustomUserNamePasswordValidator = container.Resolve<UserNamePassValidator>();
    };

这完美地工作,但如果能够从 web.config 中做到这一点会更好。如果有人知道更好的方法,请发布:)

关于wcf - 将对象注入(inject)自定义 WCF UserNamePassValidator - Autofac,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12568739/

相关文章:

java - 为静态和实例可访问性注入(inject)数据库实例

c# - 如何从客户端请求中获取 X509Certificate

wcf - Microsoft.Data.Services.Client.dll 与 System.Data.Services.Client.dll

ios - 在其他装配中重复使用装配

c# - 为什么将消息放入死信队列 (MSMQ)?

java - 通过方法创建对象时出现 Autowiring 问题

c# - 使用 Cookie 或其他方法保护 WFC/JSON 上的数据 session

asp.net - WCF/ASP.NET 身份验证

wcf - 如何为WCF netTcpBinding配置用户名/密码身份验证?

WCF 数据服务 (OData) 与 ASP.NET Web API