How to restrict SignalR server connections?
Asked Answered
U

2

6

I have a SignalR app. hosted in a Windows service (used OWIN & Katana as self hosting) and it's listening on mydomain.com:8080

On the same server, I also have an MVC application which is basically a website that connects to my SignalR hub which I mentioned above.

I want to restrict access to my SignalR app only to my MVC application. I've searched the internet but didn't come along an example of this.

Is it possible to achieve this? How can I get the information about if the connection is coming from my MVC app or from another app? Do I need to implement an authorization for my own MVC application to be able to connect to my SignalR application?

Right now, everyone on the internet can access to mydomain.com:8080/signalr endpoint which basically means a competitor can code a client that connects to my SignalR hub and use it. What are the options to prevent this scenario?

p.s: Please ask for more information -if you need- instead of just marking the post as "non constructive" because I don't know how this question can be asked more "constructive"

Uranyl answered 29/4, 2014 at 23:28 Comment(0)
S
11

I believe I have a working example, it's quick and dirty, but it should do the job, and you should be able to expand it so it'll fit your needs better:

I created a class that inherits from Microsoft.AspNet.SignalR.AuthorizeAttribute and overrode the AuthorizeHubConnection method:

[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class CustomAuthorize : AuthorizeAttribute
{

    public override bool AuthorizeHubConnection(Microsoft.AspNet.SignalR.Hubs.HubDescriptor hubDescriptor, IRequest request)
    {
        string referer = request.Headers["Referer"];
        string authority = new Uri(referer).Authority;
        if (authority == "mydomain.com:8080")
        {
            return true;
        }
        return false;
    }
}

all it does is check the Referer header's host/authority against a hard coded one, and returns true if they match.

You can then use it like this:

[CustomAuthorize]
public class ChatHub : Hub
{
    //Hub code here...
}

If CustomAuthorize returns false, the request will stop there. The hub's OnConnected() will not be triggered.

Solicit answered 1/5, 2014 at 8:24 Comment(2)
Awesome, I'll try it as soon as I get back to home. One quick question though: Will the host always be mydomain.com:8080 for every client visiting the website? I guess the mvc application passes the client's host address while connecting to SignalR am I right?Uranyl
It's better to check referer for null value : if (!string.IsNullOrEmpty(referer)) {Vaules
E
0

Just Use cors option instead of writing code.in cors allow your domain only

Evenson answered 24/10, 2017 at 10:47 Comment(1)
I think Tobias answer is also right but this is better wayAbsonant

© 2022 - 2024 — McMap. All rights reserved.