'How to add custom JWT token authentication to a .NET Framework SignalR server?
I have created a SignalR Server using .NET Framework (not .NET Core). It works fine. Now, I want to add custom JWT authentication to it.
Chat Hub:
public class ChatHub : Hub
{
[Authorize]
public void Send(string name, string message)
{
Clients.All.broadcastMessage(name, message);
}
}
I added Authorize attribute in the Hub method.
Startup.cs:
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Microsoft.Owin.Security.OAuth;
using Owin;
using SignalRServer.Authorization;
using SignalRServer.Providers;
[assembly: OwinStartup(typeof(SignalRServer.Startup))]
namespace SignalRServer
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
map.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
{
Provider = new QueryStringOAuthBearerProvider()
});
map.RunSignalR();
});
}
}
}
QueryStringOAuthBearerProvider:
using System;
using System.Threading.Tasks;
using Microsoft.Owin.Security.OAuth;
namespace SignalRServer.Providers
{
public class QueryStringOAuthBearerProvider : OAuthBearerAuthenticationProvider
{
public override Task RequestToken(OAuthRequestTokenContext context)
{
var value = context.Request.Query.Get("token");
if (!string.IsNullOrEmpty(value))
{
context.Token = value;
}
return Task.FromResult<object>(null);
}
}
}
What I want to do?
I want all the SignalR clients to send a JWT token in query string. I will custom validate this token in QueryStringOAuthBearerProvider's RequestToken method. If the validation succeeds, then the Hub method protected by Authorize attribute should be called otherwise the request is denied.
Please advise how to achieve this and what I am missing here.
PS: I want to do exactly the same thing done here but using .NET Framework (not .NET Core)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
