Integrating SignalR with existing Authorization

2019-04-29 15:21发布

问题:

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?

回答1:

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)
    {
    }
}


回答2:

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