Skip to content

Instantly share code, notes, and snippets.

@mausch
Created July 15, 2021 23:03
Show Gist options
  • Save mausch/a393e8922a642ffa826fc1243c4d7598 to your computer and use it in GitHub Desktop.
Save mausch/a393e8922a642ffa826fc1243c4d7598 to your computer and use it in GitHub Desktop.
SolrNet + MS DI auth
using System;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using SolrNet;
namespace SolrNetAuthTest
{
class Program
{
static async Task Main(string[] args)
{
/*
docker run -d --name solr -p 8983:8983 solr:8.8.2
docker exec solr solr create_core -c techproducts -d sample_techproducts_configs
docker run -d --name nginx-basic-auth -p 8087:8087 \
--link solr:solr \
-e FORWARD_HOST=solr \
-e FORWARD_PORT=8983 \
-e BASIC_AUTH_USERNAME=user \
-e BASIC_AUTH_PASSWORD=pwd \
xscys/nginx-sidecar-basic-auth
*/
var services = new ServiceCollection()
.AddSolrNet("http://localhost:8087/solr/techproducts", options =>
{
var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("user:pwd"));
options.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
})
.BuildServiceProvider();
var solr = services.GetRequiredService<ISolrBasicReadOnlyOperations<Dictionary<string, object>>>();
var response = await solr.PingAsync();
Console.WriteLine(response.QTime);
}
}
}
@mausch
Copy link
Author

mausch commented Jul 15, 2021

@nbernier
Copy link

Yes I have been across this. The problem is that we are using a Bearer token that need to be refresh after some time. Using this creates a static token that is only generate a boot time. I created a custom AddSolrNet with takes the httpClient as a parameter

   private static ISolrConnection CreateAutoSolrConnection(IServiceProvider serviceProvider,
        Func<IServiceProvider, string> urlRetriever, Action<SolrNetOptions> setupAction, HttpClient httpClient)
    {
        var solrUrl = urlRetriever(serviceProvider);
        if (string.IsNullOrWhiteSpace(solrUrl)) throw new ArgumentNullException(nameof(solrUrl));

        if (httpClient == null)
        {
            var connection = new AutoSolrConnection(solrUrl);
            if (setupAction == null) return connection;

            // Allow for custom headers to be injected.
            var options = new SolrNetOptions(connection.HttpClient);
            setupAction(options);
            return connection;
        }
        else
        {
            return new AutoSolrConnection(solrUrl, httpClient);
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment