Check authorize in SignalR attribute

左心房为你撑大大i 提交于 2019-12-05 03:28:06

AuthorizeAttribute has two more virtual methods:

  • AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request)
  • AuthorizeHubMethodInvocation(IHubIncomingInvokerContext hubIncomingInvokerContext, bool appliesToMethod)

http://msdn.microsoft.com/en-us/library/microsoft.aspnet.signalr.authorizeattribute(v=vs.118).aspx

The default implementations of both methods call UserAuthorized with the request's IPrincipal.

AuthorizeHubConnection is passed an IRequest directly.

In AuthorizeHubMethodInvocation, you can access the IRequest object from the IHubIncomingInvokerContext like so: hubIncomingInvokerContext.Hub.Context.Request.

I still struggled with this for some time trying to get the ServiceStack.Web.IRequest from the SignalR.IRequest so I could use ServiceStack's functions to request the session to see if the user had been auth'd. In the end I gave up and got the cookies from SignalR. I hope the following code snippet helps someone else nagivate this.

public class AuthorizeAttributeEx : AuthorizeAttribute
{

    public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request)
    {
        return IsUserAuthorized(request);
    }

    public override bool AuthorizeHubMethodInvocation(IHubIncomingInvokerContext hubIncomingInvokerContext, bool appliesToMethod)
    {
        return IsUserAuthorized(hubIncomingInvokerContext.Hub.Context.Request);
    }

    protected bool IsUserAuthorized(IRequest thisRequest)
    {

        try
        {
            // Within the hub itself we can get the request directly from the context.
            //Microsoft.AspNet.SignalR.IRequest myRequest = this.Context.Request; // Unfortunately this is a signalR IRequest, not a ServiceStack IRequest, but we can still use it to get the cookies.

            bool perm = thisRequest.Cookies["ss-opt"].Value == "perm";
            string sessionID = perm ? thisRequest.Cookies["ss-pid"].Value : thisRequest.Cookies["ss-id"].Value;
            var sessionKey = SessionFeature.GetSessionKey(sessionID);
            CustomUserSession session = HostContext.Cache.Get<CustomUserSession>(sessionKey);

            return session.IsAuthenticated; 

        }
        catch (Exception ex)
        {
            // probably not auth'd so no cookies, session etc.
        }

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