检查SignalR属性中的授权

时间:2014-03-26 01:52:41

标签: c# asp.net servicestack signalr authorize

我在ServiceStack上有一些服务,并在这个项目中使用SignalR。

现在,我想保护集线器连接(仅对经过身份验证的用户进行访问),但我使用ServiceStack框架身份验证..(不是asp.net身份验证)和ServiceStack的会话(写入AuthUserId ih此会话和身份验证标志)。

因此,当用户尝试连接到集线器时 - 集线器必须检查身份验证...

(是的,我可以从Hub请求Cookie(例如,方法OnConnected),但是在Authorize Attribute中检查身份验证 - 我必须在此类(不在集线器中)执行此操作

http://www.asp.net/signalr/overview/signalr-20/security/hub-authorization

所以,我创建了类

[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class AuthorizeMyAttribute : AuthorizeAttribute
{
   protected override bool UserAuthorized(System.Security.Principal.IPrincipal user)
   {
     //... how can i request Cookies? / or may be can access for ServiceStack session...
     //    and return true or false
   }
}

我能为此做些什么? 谢谢!

2 个答案:

答案 0 :(得分:7)

AuthorizeAttribute还有两个虚拟方法:

  • 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

两种方法的默认实现都会使用请求UserAuthorized调用IPrincipal

AuthorizeHubConnection直接传递IRequest

AuthorizeHubMethodInvocation中,您可以IRequest访问IHubIncomingInvokerContext对象,如下所示:hubIncomingInvokerContext.Hub.Context.Request

答案 1 :(得分:2)

我仍然在努力尝试从SignalR.IRequest获取ServiceStack.Web.IRequest一段时间,因此我可以使用ServiceStack的函数来请求会话以查看用户是否已经过身份验证。最后我放弃了并从SignalR获得了cookie。我希望以下代码片段可以帮助其他人解决这个问题。

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;
    }
}