如何在LogReceiverService(NLog)中启用安全性 [英] How can I enable Security in LogReceiverService (NLog)

查看:112
本文介绍了如何在LogReceiverService(NLog)中启用安全性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须建立一个集中的日志存储库,并决定安装实现NLog的LogReceiverService的WCF服务(通过wsHttpBinding).我遵循了此主题,其中我找到了一个有效的示例(在 bitbucket 中有一个有效的代码).

I have to make a centralized log repository and I decided to mount a WCF service implementing NLog's LogReceiverService (through wsHttpBinding). I followed this topic where I found a working example (there is a working code at bitbucket).

好,现在是问题:我想为此WCF服务添加一些安全性,通过HTTPS公开它,也许还要添加

Ok, now the problem: I would like to add some security to this WCF Service, expose it through HTTPS and maybe add an Authentication Token. I have programmed this kind of authentication earlier, so I do know how to do it, it's just I don't know how can I program that within NLog. Should I modify the Class where NLog makes the call to the WCF Method? I just can't picture how to do it. Any ideas about how to achieve this functionality is really appreciated.

推荐答案

最后,我能够做到这一点.

Finally I was able to do this.

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

Let me tell you I was able to configure the desired behavior :)

首先,我们按以下方式配置服务器:

First we configure the server as follows:

WCFService的web.config的System.ServiceModel的配置为:

The configuration of System.ServiceModel for the web.config of the WCFService is:

  <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

The 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,然后在该方法中添加凭据.

First, create a inherited class from LogReceiverWebServiceTarget and I override the method CreateWcfLogReceiverClient, then in that method add the credentials.

// 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;
    }
}

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

Then we set up the application's config file

<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

Finally we configure the 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

I posted an entire answer at the googlegroup of NLog, so enjoy it https://groups.google.com/d/msg/nlog-users/Xryu61TaZKM/Utbvrr5mwA0J

这篇关于如何在LogReceiverService(NLog)中启用安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆