Check authorize in SignalR attribute

Alexander Krylov picture Alexander Krylov · Mar 26, 2014 · Viewed 10.6k times · Source

i have some services on ServiceStack and use SignalR in this project.

And now, i would like to secure hub connection (access only for authenticated users), but i use ServiceStack framework authentication.. (not asp.net authentication) and ServiceStack's sessions (write AuthUserId ih this session and authentication flag).

So, when user trying connect to the hub -- hub must to check authentication...

(yes, i can request Cookies from Hub (method OnConnected, for example), but SignalR check authentication in Authorize Attribute - and i must do it in this class (not in hub)

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

So, i create class

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

What can i do for it? Thanks!

Answer

halter73 picture halter73 · Mar 26, 2014

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.