Integrating SignalR with existing Authorization

血红的双手。 提交于 2019-12-22 06:40:01

问题


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



来源:https://stackoverflow.com/questions/14343531/integrating-signalr-with-existing-authorization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!