Tag Archives: ActiveMQ

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:

using Amqp;
using Amqp.Sasl;
using Microsoft.Extensions.Logging;


namespace DotNETApps
{
    class Program
    {
        static async Task Main(string[] args)
        {
            using var loggerFactory = LoggerFactory.Create(builder =>
            {
                builder
                    .AddConsole()
                    .SetMinimumLevel(LogLevel.Debug);
            });

            ILogger logger = loggerFactory.CreateLogger<Program>();

            logger.LogInformation("Application started.");

            Address address = new Address("amqps://mydomain:5671");

            var factory = new ConnectionFactory();
            factory.SSL.ClientCertificates.Add(new 
                  System.Security.Cryptography.X509Certificates
                         .X509Certificate2("c:\\myclientcert.pfx", "secret"));

            factory.SASL.Profile = SaslProfile.Anonymous;

            try {
                logger.LogInformation("Connecting to broker...");
                Connection connection = await factory.CreateAsync(address);
                logger.LogInformation("Connected to broker.");

                Session session = new Session(connection);
                ReceiverLink receiver = 
                         new ReceiverLink(session, "receiver-link", "MYQUEU");

                Console.WriteLine("Receiver connected to broker.");

                Message message = await Task.Run(() => 
                          receiver.Receive(TimeSpan.FromMilliseconds(2000)));

                if (message == null)
                {
                    Console.WriteLine("No message received.");
                    receiver.Close();
                    session.Close();
                    connection.Close();
                    return;
                }

                Console.WriteLine("Received " + message.Body);
                receiver.Accept(message);

                receiver.Close();
                session.Close();
                connection.Close();
            }
            catch (Exception e)
            {
                logger.LogError(e, "An error while processing messages.");
            }

            logger.LogInformation("Application ended.");
        }
    }
}

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

A simple chat application with javascript and ActiveMQ using STOMP messaging

Here is a small chat program that can be used for building a rich chat application, or if you just want a very simple chat program for your friends. It contains sending and receiving STOMP messages from an Apache ActiveMQ topic.

Prerequisites:
* Apace ActiveMQ server which can be found here: https://activemq.apache.org/components/classic/download/ Usually no configuration needed. Just start the server (./activemq start) and everything should work ok
* Stomp.js. A helper script for handling the WebSocket communication between ActiveMQ and your javascript application. This script can be found here, courtesy of Jeff Mesnil and Mark Broadbent: https://github.com/jmesnil/stomp-websocket/tree/master/lib

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>A simple ActiveMQ chat application</title>
    
    <script src="stomp.js"></script>
    <script src="index.js"></script>
</head>
<body>
    <textarea id="chat" rows="10" cols="35"></textarea>
    <br />
    <input id="message" size="40" type="text">
    <br />
    <button id="send" type="button" onclick="send()">Send</button>
</body>
</html>

Javascript:

// Setup websocket connection
const client = Stomp.client("ws://localhost:61614/stomp", "v11.stomp");
// Setup header options
const headers = {id: 'JUST.FCX', ack: 'client'};

// Connect to ActiveMQ (via websocket)
client.connect("admin", "admin", function () {
    // Setup subscription of topic (/topic/chat)
    client.subscribe("/topic/chat",
        function (message) {
            const msg = message.body;
            // Add message to textarea
            document.getElementById("chat").value += msg + "\n";
            // Acknowledge the message
            message.ack();
        }, headers);
});

function send() {
    const message = document.getElementById("message");
    // Send message to topic (/topic/chat)
    client.send("/topic/chat", {}, message.value);
    // Reset input field
    message.value = "";
}

Tested on OSX 10.15.7 and Apache ActiveMQ v5.16.3