As the gap narrows between native mobile applications and web applications, developers are able to do more and more on the web. One common feature that most apps have are push notifications. This makes sense, because we want to be informed when something we care about has occured.
I recently decided to add push notification support to my ASP.NET Web API project. I decided to use the standard web socket solution with SignalR. Although SignalR makes it really simple to get a quick implementation going, getting it to play nice with other tooling can be more of a challenge. SignalR has it’s own dependency resolver, so getting it to work with an existing dependency injection container can be tricky. Also, by default, SignalR doesn’t know how to authenticate with an existing OAuth bearer token implementation.
In this article, I’m going to show how to get these technologies to work together to create real-time push notifications. Let’s dive in.
Install NuGet Packages
The first thing we need to do is install SignalR via NuGet and since we’re using Autofac for dependency injection, let’s install Autofac’s SignalR NuGet package.
Next, we need to add SignalR to the pipeline.
Set up Autofac integration
Out of the box, SignalR uses its own container. The nice thing is that they expose their Resolver, allowing us to override what is used. Let’s change it to use Autofac for it’s DI container.
Set up serializer and user provider
The first major issue I ran into was the fact that, by default, SignalR does not camel case outgoing objects. Meaning if you have a client app that normally receives camel-cased JSON, it won’t know how to handle this. I wanted all serialized JSON, whether via an API endpoint, or pushed via SignalR, to be camel-cased.
Create the User Id Provider
I wanted SignalR to map its connections to the ClaimsPrincipal’s NameIdentifier claim. SignalR allows you to implement your own IUserIdProvider that it will use to map socket connections to something your application cares about.
Create OAuth Provider
The last hurdle is to get SignalR to handle bearer tokens. Since our app passes the token as a header value, SignalR can’t read it because websockets do not support headers. We cancreate a new class that extends Microsoft’s OAuthBearerAuthenticationProvider to check the query string for the token.
Now that we have SignalR working with our existing infrastructure, we can start to build our real-time functionality!
As you can see, although a basic SignalR integration is pretty easy, getting it work with an existing code base can be a bit more challenging. In this article I have shown that it is possible to create a clean implementation, allowing the creation of an API with fantastic real-time functionality.