【问题标题】:How can I enable Security in LogReceiverService (NLog)如何在 LogReceiverService (NLog) 中启用安全性
【发布时间】:2014-09-14 02:22:59
【问题描述】:

我必须建立一个集中的日志存储库,我决定安装一个实现 NLog 的 LogReceiverService 的 WCF 服务(通过 wsHttpBinding)。我关注了this topic,在那里我找到了一个工作示例(bitbucket 有一个工作代码)。

好的,现在的问题是:我想为这个 WCF 服务添加一些安全性,通过 HTTPS 公开它,也许添加一个Authentication Token。我之前已经对这种身份验证进行了编程,所以我确实知道该怎么做,只是我不知道如何在 NLog 中编程。我应该修改 NLog 调用 WCF 方法的类吗?我只是无法想象如何做到这一点。任何关于如何实现此功能的想法都非常感谢。

【问题讨论】:

    标签: c# wcf wcf-security nlog


    【解决方案1】:

    我终于可以做到了。

    让我告诉你我能够配置所需的行为:)

    首先我们配置服务器如下:

    WCFService的web.config中System.ServiceModel的配置是:

      <system.serviceModel>
        <services>
          <service name="Your.Namespace.Path.To.Your.Service" behaviorConfiguration="SecureBehavior">
            <endpoint binding="wsHttpBinding" bindingConfiguration="SecureBinding" contract="NLog.LogReceiverService.ILogReceiverServer"/>
            <endpoint binding="mexHttpBinding" contract="IMetadataExchange" address="mex"/>
            <host>
              <baseAddresses>
                <add baseAddress="https://your_secure_domain.com/servicePath"/>
              </baseAddresses>
            </host>
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior name="SecureBehavior">
              <serviceDebug includeExceptionDetailInFaults="true"/>
              <serviceMetadata httpsGetEnabled="true"/>
              <serviceCredentials>
                <!--You must set your certificate configuration to make this example work-->
                <serviceCertificate findValue="0726d1969a5c8564e0636f9eec83f92e" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySerialNumber"/>
                <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="AssamblyOf.YourCustom.UsernameValidator.UsernameValidator, AssamblyOf.YourCustom.UsernameValidator"/>
              </serviceCredentials>
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <bindings>
          <wsHttpBinding>
            <binding name="SecureBinding" closeTimeout="00:00:20" openTimeout="00:00:20" receiveTimeout="00:00:20" sendTimeout="00:00:20">
              <security mode="TransportWithMessageCredential">
                <message clientCredentialType="UserName"/>
                <transport clientCredentialType="None"/>
              </security>
            </binding>
          </wsHttpBinding>
        </bindings>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
      </system.serviceModel>
    

    CustomUserNameValidator

    public class UsernameValidator : UserNamePasswordValidator
    {
        private const string UserName = "your_username_here";
        private const string Password = "your_password_here";
    
        public override void Validate(string userName, string password)
        {
            // validate arguments
            if (string.IsNullOrEmpty(userName))
                throw new ArgumentNullException("userName");
            if (string.IsNullOrEmpty(password))
                throw new ArgumentNullException("password");
    
            //
            // Nombre de usuario y contraseñas hardcodeados por seguridad
            //
            if (!userName.Equals(UserName) || !password.Equals(Password))
                throw new SecurityTokenException("Nombre de usuario o contraseña no válidos para consumir este servicio");
        }
    }
    

    然后我们去客户端配置

    首先,从 LogReceiverWebServiceTarget 创建一个继承类,并覆盖 CreateWcfLogReceiverClient 方法,然后在该方法中添加凭据。

    // we assume that this class is created in NLog.CustomExtendedService namespace
    
    [Target("LogReceiverSecureService")]
    public class LogReceiverSecureService : NLog.Targets.LogReceiverWebServiceTarget
    {
        /// <summary>
        /// Gets or sets the UserName of the service when it's authentication is set to UserName
        /// </summary>
        /// <value>The name of the endpoint configuration.</value>
        public string ServiceUsername { get; set; } 
    
        /// <summary>
        /// Gets or sets de Password of the service when it's authentication is set to UserName
        /// </summary>
        public string ServicePassword { get; set; }
    
        /// <summary>
        /// Creates a new instance of WcfLogReceiverClient.
        /// 
        /// We make override over this method to allow the authentication
        /// </summary>
        /// <returns></returns>
        protected override NLog.LogReceiverService.WcfLogReceiverClient CreateWcfLogReceiverClient()
        {
            var client = base.CreateWcfLogReceiverClient();
            if (client.ClientCredentials != null)
            {
                //
                // You could use the config file configuration (this example) or you could hard-code it (if you do not want to expose the credentials)
                //
                client.ClientCredentials.UserName.UserName = this.ServiceUsername;
                client.ClientCredentials.UserName.Password = this.ServicePassword;
            }
            return client;
        }
    }
    

    然后我们设置应用程序的配置文件

    <system.serviceModel>
        <bindings>
          <wsHttpBinding>
            <binding name="WSHttpBinding_ILogReceiverServer">
              <security mode="TransportWithMessageCredential">
                <message clientCredentialType="UserName" />
                <transport clientCredentialType="None" />
              </security>
            </binding>
          </wsHttpBinding>
        </bindings>
    
        <client>
          <endpoint address="https://your_secure_domain.com/servicePath/Logger.svc" binding="wsHttpBinding"
            bindingConfiguration="WSHttpBinding_ILogReceiverServer" contract="NLog.LogReceiverService.ILogReceiverClient"
            name="WSHttpBinding_ILogReceiverServer" />
        </client>
    
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
      </system.serviceModel>
    

    最后我们配置 NLog.config

      <extensions>
        <add assembly="NLog.CustomExtendedService"  /> <!--Assuming the custom Target was added to this assambly -->
      </extensions>
    
      <targets>
        <target xsi:type="LogReceiverSecureService"
            name="RemoteWcfLogger"
            endpointConfigurationName="WSHttpBinding_ILogReceiverServer"
            endpointAddress="https://your_secure_domain.com/servicePath/Logger.svc"
            ServiceUsername="your_username_here"
            ServicePassword="your_password_here"
            useBinaryEncoding="True"
            clientId="YourApplicationNameOrId"
            includeEventProperties="True">
        </target>
      </targets>
    

    我在 NLog 的 googlegroup 上发布了完整的答案,所以请尽情享受吧 https://groups.google.com/d/msg/nlog-users/Xryu61TaZKM/Utbvrr5mwA0J

    【讨论】:

      猜你喜欢
      • 2011-08-08
      • 2020-04-10
      • 2014-01-04
      • 1970-01-01
      • 2014-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多