Founder's blog

Using custom principal with SignalR

Jun 16 2017 :: by Alex

Sometimes you really need a custom class when accessing Context.User. Here's what you need to do to put a custom class there in SignalR:

[MyAuthorize]
public class MyHub : Hub
{
	//blah-blah
}

public class MyAuthorizeAttribute : AuthorizeAttribute
{
	public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request)
	{
		//put our custom user-principal into a magic "server.User" Owin variable
		request.Environment["server.User"] = new MyCustomPrincipal(); //your custom principal constructor

		return base.AuthorizeHubConnection(hubDescriptor, request);
	}

	public override bool AuthorizeHubMethodInvocation(IHubIncomingInvokerContext hubIncomingInvokerContext, bool appliesToMethod)
	{
		//recreate the HubContext that will do its magic with the "server.User" variable
		hubIncomingInvokerContext.Hub.Context = new HubCallerContext(
			new ServerRequest(hubIncomingInvokerContext.Hub.Context.Request.Environment),
			hubIncomingInvokerContext.Hub.Context.ConnectionId);

		return base.AuthorizeHubMethodInvocation(hubIncomingInvokerContext, appliesToMethod);
	}
}
'Using custom principal with SignalR' was written by Alex by Alex. CEO, founder