I've been working on a way of integrating SignalR Authorization Attributes with a custom authorization provider (called MVCAuthorization) I went down a few rabbit holes of trying to recreate an Authorization provider for hubs specifically, but that turned out to be far too complicated. So I was wondering, how I can integrate my existing Controller and Action Authorization with my SignalR Hubs and methods?
I figured out that you can retrieve an IAuthorization provider.
If you treat you hub as a controller, and your methods as your actions, all you have to do is create a SignalR Attribute that implements IAuthorizeHubConnection and IAuthorizeHubMethodInvocation
public class HubAuthorizeAttribute : Attribute, IAuthorizeHubConnection,IAuthorizeHubMethodInvocation
{
public virtual bool AuthorizeHubConnection(HubDescriptor hubDescriptor, Microsoft.AspNet.SignalR.IRequest request)
{
IAuthorizationProvider authorizationProvider = DependencyResolver.Current.GetService<IAuthorizationProvider>();
return authorizationProvider.IsAuthorizedController(hubDescriptor.Name);
}
public virtual bool AuthorizeHubMethodInvocation(IHubIncomingInvokerContext hubIncomingInvokerContext)
{
IAuthorizationProvider authorizationProvider = DependencyResolver.Current.GetService<IAuthorizationProvider>();
return authorizationProvider.IsAuthorizedAction(hubIncomingInvokerContext.MethodDescriptor.Hub.Name, hubIncomingInvokerContext.MethodDescriptor.Name);
}
}
Then all you have to do is put the attribute on your hub or any methods you want authorized
[HubAuthorize]
public class Message : Hub
{
public void Send(string message)
{
}
}
You should override the existing methods in the pipeline
Check authorize in SignalR attribute
http://www.asp.net/signalr/overview/signalr-20/security/hub-authorization
Overriding AuthorizeHubMethodInvocation will allow you to authorize the request while overriding UserAuthorized with allow you to authenticate (you can check the user's roles etc.
Have your HubAuthorizeAttribute inherit from AuthorizeAttribute and allow the constructor to take in a list of roles
Here's a simple example on how to handle roles http://www.jasonwatmore.com/post/2014/02/18/ASPNET-Web-API-2-Enum-Authorize-Attribute.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With