Tag Archives: .NET

AMQP with mTLS with AMQPNETLite

Every now and then you are thrown into projects were you might not be the perfect pick from start. I seldom work with .NET and this project was just that 🙂 I was asked to create a small .NET proof-of-concept application in C# that fetches messages from a AMQP broker using mTLS authentication. I post the solution so it might benefit someone else (did not find much about this on Google)
Here is the result:

01using Amqp;
02using Amqp.Sasl;
03using Microsoft.Extensions.Logging;
04 
05 
06namespace DotNETApps
07{
08    class Program
09    {
10        static async Task Main(string[] args)
11        {
12            using var loggerFactory = LoggerFactory.Create(builder =>
13            {
14                builder
15                    .AddConsole()
16                    .SetMinimumLevel(LogLevel.Debug);
17            });
18 
19            ILogger logger = loggerFactory.CreateLogger<Program>();
20 
21            logger.LogInformation("Application started.");
22 
23            Address address = new Address("amqps://mydomain:5671");
24 
25            var factory = new ConnectionFactory();
26            factory.SSL.ClientCertificates.Add(new
27                  System.Security.Cryptography.X509Certificates
28                         .X509Certificate2("c:\\myclientcert.pfx", "secret"));
29 
30            factory.SASL.Profile = SaslProfile.Anonymous;
31 
32            try {
33                logger.LogInformation("Connecting to broker...");
34                Connection connection = await factory.CreateAsync(address);
35                logger.LogInformation("Connected to broker.");
36 
37                Session session = new Session(connection);
38                ReceiverLink receiver =
39                         new ReceiverLink(session, "receiver-link", "MYQUEU");
40 
41                Console.WriteLine("Receiver connected to broker.");
42 
43                Message message = await Task.Run(() =>
44                          receiver.Receive(TimeSpan.FromMilliseconds(2000)));
45 
46                if (message == null)
47                {
48                    Console.WriteLine("No message received.");
49                    receiver.Close();
50                    session.Close();
51                    connection.Close();
52                    return;
53                }
54 
55                Console.WriteLine("Received " + message.Body);
56                receiver.Accept(message);
57 
58                receiver.Close();
59                session.Close();
60                connection.Close();
61            }
62            catch (Exception e)
63            {
64                logger.LogError(e, "An error while processing messages.");
65            }
66 
67            logger.LogInformation("Application ended.");
68        }
69    }
70}

Tested on Windows 10, AMQPNETLite v2.4.11, .NET 8.0 and Visual Studio Code 1.97.0