Integrating SignalR with existing Authorization

2019-04-29 15:31发布

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?

2条回答
ゆ 、 Hurt°
2楼-- · 2019-04-29 16:03

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

查看更多
倾城 Initia
3楼-- · 2019-04-29 16:07

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)
    {
    }
}
查看更多
登录 后发表回答