Api key authentication and SSE

I am trying to implement api key authentication with SSE and I am not sure I am doing it properly because it returns unauthorized:

class Program
{
    static void Main(string[] args)
    {
        
        ServerEventConnect connectMsg = null;
        var msgs = new List<ServerEventMessage>();
        var commands = new List<ServerEventMessage>();
        var errors = new List<Exception>();

        var client = new ServerEventsClient("http://127.0.0.1:5000","home") {
            OnConnect = e => connectMsg = e,
            OnHeartbeat = () => Console.WriteLine("heartbeat sent"),
            OnCommand = commands.Add,
            OnMessage = msgs.Add,
            OnException = errors.Add
        };

            client.Authenticate(new Authenticate()
                {
                    provider = CredentialsAuthProvider.Name,
                    UserName = "testuser"
                    , Password = "bagel"
                    , RememberMe = true
                });
               --This code fails       
/*           client.Authenticate(new Authenticate()
            {
                provider = ApiKeyAuthProvider.Name,
                UserName = "Ax6EASWHTbXj6euZ6pkZnJrseanSj6or",
                Password = ""
            
        });*/
        
        
            client.Start();
        
        //client.OnHeartbeat = () => Console.WriteLine();
        client.Handlers["chat"] = (source, message) => {
            //Deserialize JSON string to typed DTO
            //This is where you would run the query
            var chatMsg = message.Json.FromJson<ChatMessage>(); 
            "Received '{0}' from '{1}'".Print(chatMsg.Message, chatMsg.FromName);
        };

        Console.ReadLine();
    }
}

Here is the pertinent section from my apphost:

            Plugins.Add(new RazorFormat());
        Plugins.Add(new ServerEventsFeature(){LimitToAuthenticatedUsers = true,
            HeartbeatInterval = TimeSpan.FromSeconds(60),
            IdleTimeout = TimeSpan.FromSeconds(180),
            NotifyChannelOfSubscriptions = false,
            OnSubscribe = subscription => subscription.PrintDump()
        });

        SetConfig(new HostConfig
        {
            DefaultContentType = MimeTypes.Json,
            AllowSessionIdsInHttpParams = true,
        });

        this.CustomErrorHttpHandlers.Remove(HttpStatusCode.Forbidden);

        //Register all Authentication methods you want to enable for this web app.            
        Plugins.Add(new AuthFeature(
            () => new AuthUserSession(),
            new IAuthProvider[] {
                new TwitterAuthProvider(AppSettings),   //Sign-in with Twitter
                new FacebookAuthProvider(AppSettings),  //Sign-in with Facebook
                new GithubAuthProvider(AppSettings),    //Sign-in with GitHub
                new CredentialsAuthProvider(AppSettings), 
                new ApiKeyAuthProvider(AppSettings){RequireSecureConnection = false, AllowInHttpParams = true, }, 
            }));

Here are the api key’s

You would need to add the API Key to the event stream request which you can do with the EventStreamRequestFilter, e.g:

new ServerEventsClient(...) {
    EventStreamRequestFilter = req => req.AddBearerToken(apiKey)
}

Have a look at the C# Server Events Custom Authenticatoin for more examples.

1 Like

That solved my problem. Thanks for answering my question and making such a great tool.

1 Like