Yordan Dimov
Yordan Dimov

Reputation: 1

How to do AWS signature authorization and invoke elastic search using .NET Core client

I'm using OKTA authentication for AWS and I run tool which create profile in C:\Users\username.aws\credentials. I can see follow content into the file:

[my.profile] aws_access_key_id = xxxx aws_secret_access_key = xxxxx aws_session_token = xxxx

I want to invoke query to elastic search using .NET core and this profile with credentials. I'm trying to use official .NET client https://github.com/elastic/elasticsearch-net/ But can't find a way how to pass current profile 'my.profile' or SessionAWSCredentials to ElasticsearchClient.

I can get the profile using follow code:

var result = chain.TryGetProfile("my.profile", out CredentialProfile? credentials); if (result) { Environment.SetEnvironmentVariable("AWS_PROFILE", credentials.Name); Environment.SetEnvironmentVariable("AWS_ACCESS_KEY_ID", credentials.Options.AccessKey); Environment.SetEnvironmentVariable("AWS_SECRET_ACCESS_KEY", credentials.Options.SecretKey); Environment.SetEnvironmentVariable("AWS_SESSION_TOKEN", credentials.Options.Token); Environment.SetEnvironmentVariable("AWS_REGION", credentials.Region.SystemName); }

But not sure how to pass it to the client to generate Signed AWS headers to authenticate the request.

Can you someone help me and provide some code which to do it?

Upvotes: 0

Views: 755

Answers (1)

eliod
eliod

Reputation: 39

Here is an extension method that I use inside Startup to register the authenticated Elastic client.

Packages:

<PackageReference Include="NEST" Version="7.12.1" />
<PackageReference Include="Elasticsearch.Net.Aws" Version="7.1.0" />

Code:

public static void AddElasticsearch(this IServiceCollection services, IConfiguration configuration)
{
            var url = "elasticsearch_url";
            var defaultIndex = "index_name";

            var httpConnection = new AwsHttpConnection();

            var pool = new SingleNodeConnectionPool(new Uri(url));
            var config = new ConnectionSettings(pool, httpConnection);

            config.DefaultIndex(defaultIndex);
            config.DefaultFieldNameInferrer(p => p.Normalize());
            config.DisableDirectStreaming();

            var client = new ElasticClient(config);

            services.AddSingleton(client);
}

If you are using an OpenSearch client hosted by AWS, you won't be able to use newer versions of NEST and ElasticSearch packages.

Upvotes: 0

Related Questions