access elastic search using C# after setting up security

Viewed 2562

I setup security following this link. This means that I have to now enter a username and password when I access:

http://localhost:9200/

Let us say the username is un and the pw is pw234. How do I now use this in my C# code. I tried:

public static ElasticClient GetClient(string indexName)
{
    var node = new Uri(ConfigurationManager.AppSettings["Search-Uri"]);
    var settings = new ConnectionSettings(node)
      .DefaultIndex(indexName);
      settings.ThrowExceptions(alwaysThrow: true); // I like exceptions
      settings.PrettyJson(); // Good for DEBUG
      settings.RequestTimeout(TimeSpan.FromSeconds(300));
      settings.BasicAuthentication("un", "pw234");
    return new ElasticClient(settings);
}

Do I have to use BasicAuthentication? Please note that this is by no means production code. I would never hardcode the username and password like this. Thanks.

1 Answers

Basic Authentication is one authentication scheme that built-in user accounts (native realm) can use to authenticate. Other token-based authentication services are supported:

  1. Token service using Bearer (authentication scheme) tokens, based on the OAuth2 specification
  2. API keys using ApiKey (authentication scheme) tokens

Typically, for applications interacting with Elasticsearch (i.e. non-users), you would probably use one of these token based authentication services. The client exposes configuring API keys for authentication on ConnectionSettings

public static ElasticClient GetClient(string indexName)
{
    var node = new Uri(ConfigurationManager.AppSettings["Search-Uri"]);
    var settings = new ConnectionSettings(node)
      .DefaultIndex(indexName)
      .ThrowExceptions(alwaysThrow: true) // I like exceptions
      .PrettyJson() // Good for DEBUG
      .RequestTimeout(TimeSpan.FromSeconds(300))
      .ApiKeyAuthentication("<id>", "<api key>");

    return new ElasticClient(settings);
}

Bearer tokens can also be used with the client, but there is no dedicated method exposed to set the header as there is for basic authentication and api key authentication, so the .GlobalHeaders() method on ConnectionSettings and on a per request basis (through .RequestConfiguration()) needs to be used.

In addition to the native realm, Elasticsearch also supports the following realms

  1. LDAP user authentication
  2. Active Directory user authentication
  3. PKI (Client certificate) user authentication
  4. File-based user authentication
  5. SAML authentication: intended to be used in conjunction with Kibana for SSO
  6. Kerberos authentication
  7. OpenID Connect authentication
Related